我有一个要绑定(bind)到十进制的组合框?值,所以我有这段代码:
在我的 View 模型的构造函数中:
Points.Add(null);
decimal myPoint = 0;
while (myPoint <= 10)
{
Points.Add(myPoint);
myPoint = myPoint + 0.5m;
}
在我看来:
<ComboBox Name="cmbPoints" Margin="200,154,0,0" Width="120" VerticalAlignment="Top" Grid.Column="0" Grid.Row="3"
ItemsSource="{Binding Points}"
SelectedItem="{Binding PointsSelectedItem}">
问题是null元素很小,高度大约是其余item高度的1/5,所以很难选择。
但主要问题是当我选择项目时 SelectedItem 绑定(bind)没有上升,所以它没有像我预期的那样工作。
所以我想知道在组合框中有一个空项目以便能够取消选择任何选择的最佳方法是什么。
谢谢。
最佳答案
第一个问题,设置ItemTemplate属性:
<ComboBox ...
ItemsSource="{Binding Points}"
SelectedItem="{Binding PointsSelectedItem}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
对于第二个问题,很难判断是否存在具有可空项目类型和第一个项目的显式 null
值的明智解决方案。由于 SelectedItem == null
意味着没有选择 项目,因此不可能选择 null
项目。
然而,您可以使用一些标记值而不是 null
,例如-1
。然后,您可以将以下带有 DataTrigger 的样式添加到 ItemTemplate 中的 TextBlock:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="{Binding}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="-1">
<Setter Property="Text" Value=""/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
关于c# - 我怎么能在第一个位置有一个空项目的十进制组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475435/