ビューモデルプロパティにバインドされた依存プロパティを持つカスタムコントロールを作成しました。 DataContextのはWPF CustomControlは、ビューモデルに依存プロパティを2つの方法でバインドできません。
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = ViewModel = new ViewModel();
}
public ViewModel ViewModel { get; set; }
}
の背後にあるコードで設定されて
<wpf1:CustomTextBox StringProperty="{Binding StringValue}" />
ビューモデルがこの
public class ViewModel : INotifyPropertyChanged
{
public string StringValue
{
get { return m_stringValue; }
set
{
m_stringValue = value;
OnPropertyChanged("StringValue");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string m_stringValue;
}
のように見える依存関係プロパティの結合様式は、デフォルト
ことにより、2つの方法です。public static readonly DependencyProperty StringPropertyProperty =
DependencyProperty.Register(
"StringProperty",
typeof(string),
typeof(CustomTextBox),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
PropertyChangedCallback = PropertyChangedCallback
});
今、ビューモデルのプロパティStringValueが変更されたときにカスタムコントロールに通知されますが、依存関係プロパティの値を変更すると、ビューモデルの値は変更されません。
private static void PropertyChangedCallback(DependencyObject dO,
DependencyPropertyChangedEventArgs e)
{
var textBox = (CustomTextBox) dO;
if (textBox.StringProperty == null)
return;
DoSomething(textBox.StringProperty)
textBox.StringProperty = null;
}
私はビューのモデルの値を "some value"に設定した場合、カスタムコントロールでその文字列を使用してnullにリセットする必要があります。これまでのところ、これはうまくいきますが、ビューモデルの値は同期化されておらず、nullではなく「一部の値」のままです。どのようにこれを行うにはどのようなアイデア?なぜ、双方向バインディングがそのように機能しないのですか?
ありがとうございました。
O/Tですが、 'public ViewModel ViewModel {get {ViewModelとしてDataContextを返します。 }セット{DataContext =値; }} 'は、型付きのプロパティを' DataContext'と同期させておく心配を省きます。 –