我有一個INotifyPropertyChanged從教程中復制的處理模型:
public event PropertyChangedEventHandler? PropertyChanged;
protected void Notify(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
當我更新類的成員時,我呼叫處理程式:
public string? Id
{
get => _id;
set
{
if (value != _id)
{
_id = value;
Notify(nameof(Id));
}
}
}
在我后面的視圖代碼中:
private Goal _goal;
public GoalControl()
{
InitializeComponent();
this._goal = new MyGoal();
this.DataContext = _goal;
Binding binding = new Binding("Text");
binding.Source = _goal.Id;
binding.Mode = BindingMode.TwoWay;
_ = Id.SetBinding(TextBox.TextProperty, binding);
}
但是該視圖不會對欄位進行任何更改。當我除錯時,我發現它PropertyChanged總是為空。我應該如何將其設定為有用的值?
順便說一下,這是在用戶控制元件中,它將動態生成,因此我認為我無法從 XAML 進行系結。
uj5u.com熱心網友回復:
假設這Id是您的 GoalControl 中的 TextBox,您將其 Text 屬性系結到IdDataContext 中的 MyGoal 物件的 ,如下所示。
您不設定SourceBinding的屬性,因為源物件應由當前 DataContext 提供。另請注意,這TwoWay是 TextBox.Text 屬性的默認系結模式,不需要顯式設定。
public GoalControl()
{
InitializeComponent();
_goal = new MyGoal();
DataContext = _goal;
Binding binding = new Binding("Id");
Id.SetBinding(TextBox.TextProperty, binding);
}
系結也可以用 XAML 撰寫:
<TextBox Text="{Binding Id}"/>
由于這是在 UserControl 中,因此您根本不應設定 DataContext。UserControls 與任何其他控制元件一樣,不應具有像 MyGoal 物件那樣的“私有”視圖模型。
UserControl 將改為公開一個依賴屬性Id,該屬性在您使用控制元件時系結,例如
<local:GoalControl Id="{Binding SomeViewModelId}"/>
在 UserControl 的 XAML 中,系結到自己的屬性會將 Source 物件指定為 RelativeSource:
<TextBox Text="{Binding Id,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376970.html
標籤:小白
上一篇:C#WPF根據資料更改DataGrid行(背景)顏色
下一篇:如何禁用按鈕的Enter鍵
