wpf – 如何将“绑定”值传递给依赖项属性
我的应用程序有一个MainWindow.在这个中,有一个控件,一个ListBox,绑定到MainWindowViewModel的一个属性.此属性是UserControl,类型为CriteriaVm
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). “输出”窗口中显示以下错误
确定错误消息告诉我它正在ProperitesVm中寻找MyString …我应该在CriteriaVm中寻找MyString.这意味着我需要使用RelativeSource,我认为它是1级和UserControl类型.所以我更新到: <vm:PropertiesVm ThresholdName="{Binding Path=MyString,RelativeSource={RelativeSource AncestorLevel=1,AncestorType=UserControl,Mode=FindAncestor}}" /> 我得到一个稍微不同的问题,但似乎存在相同的潜在错误
目前,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"; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |