Reputation: 1156
Is it possible to bind the items of the control within the user control to a property whose name is specified via binding?
Something like this, but without the error produced:
<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>
Where
CheckListItems
(DP) is a collection of items (IList<SomeCustomContainerType>)
ItemPropertyName
(DP) is the name of the property within the SomeCustomContainerType
that should be displayed as a check box textRoot
is the name of the User ControlThe exception in this case is (expectedly) as following:
A 'Binding' cannot be set on the 'Path' property of type 'Binding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
Basically I want to pass the property name whose text should be displayed in a checkbox somehow from outside. It doesn't have to be bindable, but should be settable from the XAML consuming the user control.
Upvotes: 0
Views: 542
Reputation: 415
Simply replace your line with this:
<CheckBox Content="{Binding ItemPropertyName}" />
Upvotes: 0
Reputation: 7906
have you tried using DisplayMemberPath?
here is an example of how to use it
try this, and see if it works:
<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>
Upvotes: 1
Reputation: 5566
A possibility would be to use a ValueConverter with a ConverterParameter as the name of the Property. In the ValueConverter implementation you could load the the Value with Reflection.
the converter could look something like that:
[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;
}
}
Upvotes: 0