【发布时间】:2014-04-03 01:45:30
【问题描述】:
我有 ViewModel
public class VM: DependencyObject, INotifyPropertyChanged
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(VM), new PropertyMetadata(""));
public int Length
{
get
{
return Text != null ? Text.Length : 0;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
并查看它
<UserControl.DataContext>
<local:VM Text="{Binding ControlText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
</UserControl.DataContext>
<StackPanel>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="{Binding Length}"/>
</StackPanel>
是的,视图在后面的代码中也有依赖属性
public string ControlText
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("ControlText", typeof(string), typeof(Writer), new PropertyMetadata(""));
输出日志出错
System.Windows.Data 错误:4:无法找到与引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.UserControl',AncestorLevel='1''的绑定源。绑定表达式:路径=控制文本;数据项=空;目标元素是“VM”(HashCode=21019086);目标属性是“文本”(类型“字符串”)
当这项技术奏效时,我将拥有构建视图模型的工具。 也许有人知道如何将此视图属性绑定到 viewmodel 属性或知道如何正确执行此操作:)
【问题讨论】:
标签: c# wpf mvvm properties dependencies