![](/img/trans.png)
[英]Binding ItemSource property in a custom control that contains a Picker
[英]Access ItemSource Properties Custom Control
我正在尝试创建一个包含复选框和文本的自定义列表框。 这是自定义控件类:
public FilterChoices()
{
InitializeComponent();
}
public IEnumerable ItemsSource
{
get { return (IEnumerable) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable),
typeof(FilterChoices));
自定义控制xaml:
<ListBox x:Name="FilteredItems" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" Height="Auto" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<CheckBox Content="{Binding Data}" IsChecked="{Binding IsChecked}"/>
<!--<CheckBox Content="{Binding Path=Data, ElementName=FilterChoiceControl}" IsChecked="{Binding Path=IsChecked, ElementName=FilterChoiceControl}"/>-->
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
传入的对象列表:
public class FilterItems
{
public string Data { get; set; }
public bool IsChecked { get; set; }
}
我在我的MainWindow代码中手动设置ItemSource。 如果我在自定义控件中的setter上放置一个断点,我可以看到它正在填充正确的数据。 但是,列表框在加载时显示为空。 如果我不使用自定义控件并手动将列表框添加到我的MainWindow的xaml中,则列表框将按预期填充。 我想使用自定义控件,所以我可以添加除列表框和复选框之外的其他控件
可能问题在于您绑定数据的方式。 您尚未在FilterChoices中发布ItemsSourceProperty的用途。 无论你说什么,下面的代码完美地绑定数据:
主窗口:
public MainWindow()
{
InitializeComponent();
var lst = new List<FilterItems>();
for (int i = 0; i < 100; i++)
{
lst.Add(new Temp.FilterItems()
{
Data = $"Item {i + 1}",
IsChecked = i % 2 == 0
});
}
this.DataContext = lst;
}
Xaml:
<Window x:Class="MyNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:temp="clr-namespace:MyNamespace"
mc:Ignorable="d"
Title="Test Assembly Runner" Height="350" Width="525">
<temp:CustomControl DataContext="{Binding}" />
</Window>
Custom Control:
<UserControl x:Class="MyNamespace.CustomControl"
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:local="clr-namespace:MyNamespace"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<ListBox x:Name="FilteredItems" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" Height="Auto" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<CheckBox Content="{Binding Data}" IsChecked="{Binding IsChecked}"/>
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</UserControl>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.