[英]UserControl DataContext Binding
我的解決方案中有三個項目:
在我的MainWindow中,我想將UserControl與UIProcess的ViewModel一起使用。
首先,我在MainWindow中設置UserControl:
<TabItem Header="Editor">
<Grid>
<cel:ConfigEditorView DataContext="{Binding ConfEditModel, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</TabItem>
我不知道在這里需要這些屬性中的哪一個,因此我將所有屬性放在一起,但仍然無法正常工作。
然后在MainViewModel中設置它:
public ConfigEditorViewModel ConfEditModel { get; set; }
使用綁定到Button的簡單方法:
private void doSomething()
{
ConfEditModel = new ConfigEditorViewModel("Hello World");
}
我的ConfigEditorViewModel基本上是這樣的:
public class ConfigEditorViewModel : ViewModelBase
{
private string _Description;
public string Description
{
get
{
return _Description;
}
set
{
_Description = value;
base.RaisePropertyChanged();
}
}
public ConfigEditorViewModel(string t)
{
Description = t;
}
}
該說明綁定到我的UserControl中的TextBox。
<TextBox Grid.Row="1" Grid.Column="1" Margin="0,0,0,10" Text="{Binding Description}"/>
當我啟動應用程序並單擊“按鈕”時,文本框應包含“ Hello World”,但它為空。
我做錯了什么?
我給你一個一般的答案:
在“真實(要與具有不同屬性名稱的不同視圖模型一起使用的用戶控件)”用戶控件中,您只能將其綁定到自己的DependencyProperties上,並使用ElementName或RelativeSource綁定進行綁定,並且永遠不要在UserControl中設置DataContext 。
<UserControl x:Name="myRealUC" x:class="MyUserControl">
<TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Path=TwoWay}"/>
<UserControl>
如果這樣做,您可以在任何視圖中輕松使用此Usercontrol,例如:
<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>
為了完整性:Dependency屬性
public readonly static DependencyProperty MyOwnDPIDeclaredInMyUcProperty = DependencyProperty.Register(
"MyOwnDPIDeclaredInMyUc", typeof(string), typeof(MyUserControl), new PropertyMetadata(""));
public bool MyOwnDPIDeclaredInMyUc
{
get { return (string)GetValue(MyOwnDPIDeclaredInMyUcProperty); }
set { SetValue(MyOwnDPIDeclaredInMyUcProperty, value); }
}
您的視圖模型(以及可選的模型)需要實現INotifyPropertyChanged 。
綁定不是魔術。 沒有內置的機制允許在普通的舊屬性的值更改時通知代碼。 您必須對其進行輪詢,以檢查是否發生了更改,從性能角度來看這將是非常糟糕的。
因此,綁定將查看綁定到的對象,並查看它們是否實現INotifyPropertyChanged,如果是,則將訂閱PropertyChanged事件。 這樣,當您更改屬性並觸發事件時,將通知綁定並更新UI。
警告,您必須實現接口並正確使用它。 這個例子說的是2010年 ,但是效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.