[英]User control in Data template not shown
我有这个 ComboBox
<ComboBox x:Name="Renderer" ItemsSource="{Binding RendererItems}"
ItemTemplate="{StaticResource DropDownItemTemplate}" SelectedIndex="0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<ei:CallMethodAction TargetObject="{Binding}"
MethodName="RendererItemsSelectionChanged"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
还有这个项目的数据模板
<DataTemplate x:Key="DropDownItemTemplate">
<StackPanel Orientation="Horizontal">
<UserControl Content="{Binding Icon}" Width="24" Height="24"/>
<TextBlock Text="{Binding Text}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0"/>
</StackPanel>
</DataTemplate>
数据来自:
public ObservableCollection<ComboBoxItemModel> RendererItems { get; set; } = new ObservableCollection<ComboBoxItemModel>();
public MainWindowViewModel()
{
RendererItems.Add(new ComboBoxItemModel() { Icon = new RenderedIcon(), Text = "Rendered" });
RendererItems.Add(new ComboBoxItemModel() { Icon = new WireframeIcon(), Text = "Wireframe" });
RendererItems.Add(new ComboBoxItemModel() { Icon = new ShadedIcon(), Text = "Shaded" });
RendererItems.Add(new ComboBoxItemModel() { Icon = new HiddenLinesIcon(), Text = "Hidden Lines" });
}
ComboBoxItemModel class 定义如下:
public class ComboBoxItemModel
{
public UserControl Icon { get; set; }
public string Text { get; set; }
}
我第一次单击 Combo 时显示如下:
如您所见,所选项目没有图标
我第二次单击 Combo 时显示如下:
现在我选择的项目没有图标。 但我希望组合项目总是有一个图标。
UIElement - 就像您的UserControl Icon
- 只能有一个父元素,因此只能在可视树中出现一次。 您根本不应该将 UIElement 作为视图 model 数据项。
为了给 model 一个图标,使用一个 bitmap 或一个 DrawingImage 中的绘图:
public class ComboBoxItemModel
{
public ImageSource Icon { get; set; } // assign a DrawingImage
public string Text { get; set; }
}
和
<DataTemplate x:Key="DropDownItemTemplate">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Icon}" Width="24" Height="24"/>
<TextBlock Text="{Binding Text}" .../>
</StackPanel>
</DataTemplate>
使用 UserControl 图标的替代方法可能是使用 VisualBrush 填充 Rectangle:
<DataTemplate x:Key="DropDownItemTemplate">
<StackPanel Orientation="Horizontal">
<Rectangle Width="24" Height="24">
<Rectangle.Fill>
<VisualBrush Visual="{Binding Icon}"/>
</Rectangle.Fill>
</Rectangle>
<TextBlock Text="{Binding Text}" .../>
</StackPanel>
</DataTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.