如何使用MainViewModel属性绑定UserControl DepenpencyProperty。
MainViewModel.cs
public class MainViewModel : ViewModelBase
{
public MainModel Model{get;set;}
public MainViewModel()
{
Model = new MainModel();
}
}
MainModel.cs
public class MainModel:ObservableObject
{
private string text;
public string Text
{
get{return text;}
set{text=value;RaisePropertyChanged(()=>Text)}
}
MainView.xaml
<Window
DataContext="{Binding Main, Source={StaticResource MainLocator}}">
<someusercontrol:controlEx DP={Binding Model.Text} />
</Window>
ControlEx.xaml
<UserControl DataContext="{Binding Source={StaticResource Locator},Path=NewMain}" x:Class="someusercontrol.controlEx ">
</UserControl>
ControlEx.xaml.cs
public partial class ControlEx:UserControl
{
public string DP
{
get
{
return (string)GetValue(DPProperty);
}
set
{
SetValue(DPProperty, value);
}
}
public static readonly DependencyProperty DPProperty =
DependencyProperty.Register(
"DP",
typeof(string),
typeof(ControlEx),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnDPPropertyChanged)));
private static void OnDPPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ControlEx source = d as ControlEx ;
(source.DataContext as MainViewModel).Model.UserText= (string)e.NewValue;
//// some actions
}
}
此示例对我不起作用,ControlEx中的方法SetValue不会引发。如果我将DP = {Binding Model.Text}更改为DP = {&#34; 123&#34;},一切正常。
解决
将绑定更改为
<Window
DataContext="{Binding Main, Source={StaticResource MainLocator}}">
<someusercontrol:controlEx DP={Binding Main.Model.Text, Source={StaticResource MainLocator}} />
</Window>
它有效。