CriteriaVm有一个名为MyString的字符串属性
在标准视图中,我有以下代码
<UserControl x:Class="CompoundInterests.View.CriteriaView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:CompoundInterests.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="600">
<UserControl.Resources>
<ResourceDictionary Source="../Dictionary.xaml" />
</UserControl.Resources>
<Grid>
<Border>
<Expander Header="{Binding MyString}" >
<vm:PropertiesVm ThresholdName="{Binding MyString}" />
</Expander>
</Border>
</Grid>
</UserControl>
如您所见,我在两个地方绑定了MyString.扩展器中的绑定工作正常,vm中的绑定:PropertiesVm没有(使用Dependency Properites). “输出”窗口中显示以下错误
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=MyString; DataItem=null; target element is ‘PropertiesVm’ (HashCode=5991653); target property is ‘ThresholdName’ (type ‘String’)
确定错误消息告诉我它正在ProperitesVm中寻找MyString …我应该在CriteriaVm中寻找MyString.这意味着我需要使用RelativeSource,我认为它是1级和UserControl类型.所以我更新到:
<vm:PropertiesVm ThresholdName="{Binding Path=MyString, RelativeSource={RelativeSource AncestorLevel=1,AncestorType=UserControl,Mode=FindAncestor}}" />
我得到一个稍微不同的问题,但似乎存在相同的潜在错误
System.Windows.Data Error: 4 : Cannot find source for binding with reference ‘RelativeSource FindAncestor, AncestorType=’System.Windows.Controls.UserControl’, AncestorLevel=’1”. BindingExpression:Path=MyString; DataItem=null; target element is ‘PropertiesVm’ (HashCode=24649639); target property is ‘ThresholdName’ (type ‘String’)
目前,PropertiesVm只有依赖属性,PropertiesView只是一个空网格.这样我就可以先处理这个错误,然后再担心下一个绑定阶段.
我不明白为什么我收到错误信息或我做错了什么.
如果需要,我可以愉快地提供更多代码.现阶段的项目很早,因此,代码最少.
<Style TargetType="{x:Type ns:YourViewModel}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ns:YourViewModel}">
<Grid>
<TextBlock Text="{Binding ThresholdName,
RelativeSource={RelativeSource TemplatedParent}}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
视图模型代码与您显示的内容几乎没有变化:
public class YourViewModel: Control
{
public static readonly DependencyProperty ThreshNameProperty = DependencyProperty.Register("ThresholdName", typeof(string), typeof(PropertiesVm), new PropertyMetadata(string.Empty));
public string ThresholdName
{
get { return GetValue(ThreshNameProperty).ToString(); }
set { SetValue(ThreshNameProperty, value); }
}
}
你并不完全清楚“MyStringValue”是什么,所以我希望它是MainWindow的正常属性. MainWindow将创建一个控件实例,将“ThresholdName”设置为此“MyStringValue”属性:
<Grid>
<ns:YourViewModel ThresholdName="{Binding MyStringValue}"/>
</Grid>
最后你的MainWindow代码是:
public string MyStringValue { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyStringValue = "dog";
}
