0

ControlTemplateのようなカスタム コントロールがあります (簡略化)。

<ControlTemplate TargetType="CustomControl">
    <Grid>
        <Grid.Resources>
            <DataTemplate TargetType="CustomClassA">
                <TextBlock Text={Binding ClassASpecificProperty}" />
            </DataTemplate>

            <DataTemplate TargetType="CustomClassB">
                <TextBlock Text={Binding ClassBSpecificProperty}" />
            </DataTemplate>
        </Grid.Resources>

        <ContentControl Content="{TemplateBinding Content}" />
    </Grid>
</ControlTemplate>

Contentこれの利点は、タイプ (A または B) に依存する特定の が、DataTemplateタイプごとに定義された s によって異なって表示されることです。

でも。sだけではない場合もありますTextBlock。これらの DataTemplates にボタンがあったと想像してください。Click特定のメソッドでイベントをサブスクライブしたい場合があります。ただし、これらのコントロール テンプレートは通常 にあるため、対応するハンドラーのメソッドを配置するためのコード ビハインドResourceDictionaryはありません。Click

私はまだ3つの異なる解決策を見ました:

  • コード ビハインド ファイルが添付された CustomResourceDictionary の作成
  • メソッドをオーバーライドしOnApplyTemplate(これはよくわかりませんが)、プログラムでイベントをサブスクライブします
  • 添付されたメッセージを操作し、「ViewModel」で UI ロジックを処理します。醜い!

これを達成するためのベストプラクティスは何ですか? それとも、「より良い」解決策はありますか? そして、パフォーマンスはどうですか?

4

1 に答える 1

0

DelegateCommandを使用して、ボタンなどを ViewModel のコマンドにバインドできます。

<Button Command="{Binding MyCommand}"/>

ビューモデル:

public DelegateCommand MyCommand {get;set;} //INotifyPropertyChanged, etc.

private void ExecuteMyCommand()
{
    //Do stuff here.
}

public MyViewModel()
{
    MyCommand = new DelegateCommand(ExecuteMyCommand);
}
于 2013-02-14T16:01:02.983 に答える