自定义用户控件,在列表框中嵌套用户控件
本文关键字:用户 控件 嵌套 自定义 列表 | 更新日期: 2023-09-27 18:09:33
我试图获得一个自定义UserControl在ListBox中渲染,但没有任何东西被渲染。我遇到了这个问题和解决方案,它适用于简单的例子,但我的情况有点不同。我有一个PersonControl
用于Person
对象,一个CoupleControl
可以引用两个PersonControl
控件。
我在CoupleControl
中尝试了一些没有工作的事情。我注释掉了其中一种方法:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Control:PersonControl Grid.Column="0"
x:Name="LeftPerson" />
<Control:PersonControl Grid.Column="1"
x:Name="RightPerson" />
<!-- This is how I'd like to do it in case I create other controls
I wish to replace the PersonControls (e.g. AnimalControl) -->
<!--<UserControl Grid.Column="0"
x:Name="LeftPerson" />-->
<!--<UserControl Grid.Column="1"
x:Name="RightPerson" />-->
</Grid>
列表框的相关WPF片段:
<ListBox Grid.Row="1"
ItemsSource="{Binding Persons}">
<ListBox.ItemTemplate>
<DataTemplate>
<Control:CoupleControl />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在代码后面:
public ObservableCollection<CoupleControl> Persons { get; private set; }
Person joe = new Person("Joe", "Smith", Person.SexType.Male);
Person jane = new Person("Jane", "Smith", Person.SexType.Female);
PersonControl joeControl = new PersonControl();
PersonControl janeControl = new PersonControl();
joeControl.DataContext = joe;
janeControl.DataContext = jane;
CoupleControl coupleControl = new CoupleControl();
coupleControl.LeftPerson.DataContext = joe;
coupleControl.RightPerson.DataContext = jane;
//coupleControl.LeftPerson.Content = joeControl; // Also doesn't work
//coupleControl.RightPerson.Content = janeControl; // Also doesn't work
Persons.Add(coupleControl);
有人能帮我得到的CoupleControl在一个列表框渲染?
您的方法对我的口味来说有点过于代码繁重,为什么不在XAML中设置DataContext ?
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Control:PersonControl DataContext="{Binding LeftPerson}" />
<Control:PersonControl DataContext="{Binding RightPerson}" Grid.Column="1" />
</Grid>
或者干脆放弃UserControls
,如果他们不是那么复杂的话?在这种情况下,使用DataTemplates
可以更快更简单。假设我们在windows资源中定义了Person
和Couple
的模板(Couple只是一个具有LeftPerson和RightPerson属性的类):
<Window.Resources>
<DataTemplate x:Key="personTemplate" DataType="TestWPF:Person">
<Border BorderThickness="1" BorderBrush="Green" CornerRadius="5">
<StackPanel>
<TextBlock Text="{Binding FirstName}" />
<TextBlock Text="{Binding LastName}" Margin="3,0,0,0" />
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="coupleTemplate" DataType="TestWPF:Couple">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ContentControl Content="{Binding LeftPerson}"
ContentTemplate="{StaticResource personTemplate}" />
<ContentControl Content="{Binding RightPerson}"
ContentTemplate="{StaticResource personTemplate}" Grid.Column="1" />
</Grid>
</DataTemplate>
</Window.Resources>
然后为你的ListBox设置ItemTemplate
:
<ListBox Grid.Row="1" ItemsSource="{Binding Persons}" ItemTemplate="{StaticResource coupleTemplate}" />
这样你就可以为你需要的类型制作更多的模板,只需在ListBox中用一行设置它们。