是否可以在不显式指定的情况下自动神奇地绑定到path
本文关键字:情况下 神奇 path 绑定 是否 | 更新日期: 2023-09-27 18:06:44
我不确定这是否可能,虽然(懒惰…hrmp……有效率)我还是想问。DataGrid具有根据发送到它的元素的字段自动创建列的功能。
然而,在我的应用程序中,我们已经禁用了数据编辑,相反,当用户单击一行时,会弹出一个对话框,用于编辑所单击行对应的对象的每个字段的值。
我发送的对象对应的行点击到对话框,并使用它作为它的数据上下文。这意味着,目前,我需要显式地指定每个字段的绑定,如下所示。
<TextBox x:Name="SomeName"
Style="{StaticResource DefaultTextBoxStyle}"
Text="{Binding Path=SomeProperty,Mode=TwoWay}" />
我很好奇是否有可能以某种方式使字段"有点意识到"它们需要从数据上下文的字段(基于它们的名称或类似的)中选择它们的绑定值。像这样。
<TextBox x:Name="CertainString"
Style="{StaticResource DefaultTextBoxStyle}"
Text="{Binding CertainStringOrSomething}" />
我认为实现这一目标的唯一方法(如果我对你的问题有正确的理解)是用MultiValueConverter
来做到这一点。您将整个ViewModel和当前xhtml元素的名称传递给转换器。
<TextBlock Name="FirstName">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource propertyResolver}">
<Binding RelativeSource="{RelativeSource Self}" Path="Name"/>
<Binding Path="Person"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
在转换器中,您使用反射访问属性并返回它:
public class PropertyResolver : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
if (!(values[1] is Person)) throw new ArgumentException("please pass a person");
var person = (Person)values[1];
var property = values[0].ToString();
return person.GetType().GetProperty(property).GetValue(person, null);
}
}
(ExampleData: ViewModel包含属性public Person Person { get; set; }
, Person类在本例中包含属性FirstName
)