定义要绑定的自定义属性

时间:2011-03-21 15:19:24

标签: wpf user-controls binding

是否可以将用户控件中控件的项绑定到通过绑定指定名称的属性?

像这样,但没有产生错误:


    <ItemsControl ItemsSource='{Binding Path=CheckListItems, ElementName=Root}'>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <!-- What should I put below to replace the inner binding? -->
                <CheckBox Content='{Binding Path={Binding Path=ItemPropertyName, ElementName=Root}, Mode=OneTime}' />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

其中

  • CheckListItems(DP)是项目(IList<SomeCustomContainerType>)
  • 的集合
  • ItemPropertyName(DP)是SomeCustomContainerType中应显示为复选框文本的属性名称
  • Root是用户控件的名称

在这种情况下的例外(预期)如下:

A 'Binding' cannot be set on the 'Path' property of type 'Binding'.
A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

基本上我想传递属性名称,其文本应该以某种方式从外部显示在复选框中。它不必是可绑定的,但应该从消耗用户控件的XAML中设置。

3 个答案:

答案 0 :(得分:1)

您是否尝试过使用DisplayMemberPath

here是如何使用它的示例

试试这个,看看它是否有效:

<ItemsControl ItemsSource="{Binding Path=CheckListItems, ElementName=Root}" DisplayMemberPath="{Binding ItemPropertyName, ElementName=Root}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- What should I put below to replace the inner binding? -->
            <CheckBox Content="{Binding Mode=OneTime}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

答案 1 :(得分:0)

可能的情况是使用ValueConverter和ConverterParameter作为Property的名称。在ValueConverter实现中,您可以加载带反射的值。

转换器可能看起来像这样:

[ValueConversion(typeof(string), typeof(string))]
public class ReflectionConverter : IValueConverter
{
    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (parameter != null)
        {
            Type type = value.GetType();
            System.Reflection.PropertyInfo prop = type.GetProperty (parameter.ToString());
            return prop.GetValue(value, null);
        }
        return value;
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
  • 添加错误处理...

答案 2 :(得分:0)

只需用以下内容替换您的行:

<CheckBox Content="{Binding ItemPropertyName}" />
相关问题