c# - 使用 ItemTemplating 更改网格的内容
问题描述
现在的情况
我有网格,这个网格有 3 行。每行包含一个我的用户控件。每个 UserControl 都被硬编码到 Grid 行之一:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<Grid>
<local:myUserControl DependencyProperty1 = "{Binding Property1}" DependencyProperty2 = "{Binding Property2}" />
<Stackpanel><Button/><Combobox/></StackPanel>
</Grid>
<Grid Grid.Row="1">
<local:myUserControl DependencyProperty1 = "{Binding Property1}" DependencyProperty2 = "{Binding Property2}" />
<Stackpanel><Button/><Combobox/></StackPanel>
</Grid>
[...]
</Grid>
我的任务
我的控件数量超出了我的窗口所能容纳的数量。我想让用户在所有可用的控件之间进行切换,方法是在 中选择他喜欢的控件,ComboBox
然后按Button
.
我考虑过使用 ItemTemplating 来实现这一点。我发现这篇文章是关于如何处理不同类型的 DataTypes,这很有帮助。然而我觉得这里的列表有点多余,因为它总是只有一个项目,但我不知道该用什么来代替。
我的问题
是否有更好的解决方案,因为使用只有一个项目的列表,或者是否有更好的方法来创建“可交换”控件?
解决方案
此处的代码将实现一个控件,其内容根据组合框的值而变化。这只是使用省略号,但如果需要,您可以将自己的用户控件插入 ContentControl:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ComboBox Name="MyComboBox">
<ComboBoxItem Content="Fish"/>
<ComboBoxItem Content="Chips"/>
</ComboBox>
<Grid Grid.Row="1">
<ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="Content">
<Setter.Value>
<Ellipse Fill="Green" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedItem.Content}" Value="Fish">
<Setter Property="Content">
<Setter.Value>
<Ellipse Fill="Red" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedItem.Content}" Value="Chips">
<Setter Property="Content">
<Setter.Value>
<Ellipse Fill="Blue" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
</Grid>
推荐阅读
- cloudflare - cloudflare worker 重写主机头
- javascript - 单击返回箭头和日期返回;单击前进箭头和日期以前进
- python - 从类体调用类方法
- android - android中websockets的证书固定
- python - 网页抓取时面临“''block block-block-content block-block-contente1ace621-3e0d-4b51-848d-aa830cd4a1c5”''的问题
- xcode - 找不到模块映射文件'/Users/"my_flutter_project_path"/ios/Pods/Headers/Private/openssl_grpc/BoringSSL-GRPC.modulemap'?
- json - 在Java中将JSON字符串转换为Avro GenericRecord(生成的Schema是通过相同的Json字符串)
- android - 获取 java.lang.IllegalArgumentException: width and height must be > 0 error while initializing Mat in android
- c# - 如果存在重复节点,如何查找节点
- flutter - 如何将地图列表获取到日历?[扑]