1

次のようなデータテンプレートがあります。

<DataTemplate DataType="{x:Type mvvm:ComponentViewModel}">
   <v:UCComponents></v:UCComponents>
</DataTemplate> 

UCComponent は、ID というパブリック プロパティを持つユーザー コントロールです。ComponentViewModel には ID というプロパティもあります。ViewModel のプロパティのセッターで UCComponent ID プロパティを設定したいと思います。どうやってやるの?

これは私が試したことです:

private string _ID;
public string ID 
{
    set { ((UCComponents)((DataTemplate)this).LoadContent()).ID = value; } 
}

エラー: これは ComponentViewModel から DataTemplate に変換できません。どんな助けでも大歓迎です。

私は MVVM の設計パターンに忠実ではありません。これがおそらく不満の原因ですが、テンプレートで使用されている UserControl にアクセスする方法はありますか?

アマンダ


助けてくれてありがとう、でもうまくいかない。ID のゲッターとセッターは呼び出されません。これは私のコードです:

public static DependencyProperty IDProperty = DependencyProperty.Register("ID",     typeof(Guid), typeof(UCComponents));
public Guid ID
{
    get
    { return (Guid)GetValue(IDProperty); }
    set
    { 
        SetValue(IDProperty, value);
        LoadData();
    }
}

UserControl を DependencyObject にすることはできません。それはおそらく問題ですか?

4

2 に答える 2

0

次のように、ユーザー コントロール (UCComponents.xaml.cs) に依存関係プロパティを追加できます。

    public static DependencyProperty IDProperty = DependencyProperty.Register(
    "ID",
    typeof(Object),
    typeof(BindingTestCtrl));

    public string ID
    {
        get
        {
            return (string)GetValue(IDProperty);
        }
        set
        {
            SetValue(IDProperty, value);
        }
    }

次に、使用してバインドできます

<DataTemplate DataType="{x:Type mvvm:ComponentViewModel}">
    <v:UCComponents ID="{Binding ID}" />
</DataTemplate>

別の解決策は、次のような方法でユーザー コントロールの DataContextChanged イベントを処理することです。

    private ComponentViewModel _data;

    private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        _data = e.NewValue as ComponentViewModel;
        this.ID = _data.ID;
    }
于 2012-06-26T03:35:00.257 に答える