使用 Silverlight 中的转换器绑定到 ComboBox
我有一个数值,希望在显示时将其转换为更用户友好的字符串格式。我已经有一个名为 FlightLevelConverter
的 IValueConverter,我用它来为正常的 TextBlock
UI 项目执行此操作,并且运行良好。
我现在希望将转换器应用于海拔选择的 ComboBox
,但我无法让它工作。
这是我用于 ComboBox 的 XAML 的相关部分:
<UserControl.Resources>
<status:FlightLevelConverter x:Key="FlightLevelConverter"/>
</UserControl.Resources>
...
<ComboBox x:Name="AltitudeCombo" Grid.Row="0" Grid.Column="3" Width="100">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FlightLevelConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
它显示未转换的数值,而不是漂亮的字符串值。我没有收到任何错误,如果我在转换器中设置断点,它不会被命中,这表明转换器从未被调用。
我花了整个上午的时间在互联网上搜索,特别是在 StackOverflow 上搜索,试图发现我做错了什么,但没有发现任何有用的东西。
为什么我的转换器没有被调用?我做错了什么?
I have a numeric value that I wish to be converted to a more user-friendly string format when it's displayed. I already have an IValueConverter called FlightLevelConverter
that I'm using to do this for a normal TextBlock
UI item where it works fine.
I now wish to apply the converter to a ComboBox
of altitude choices, but I can't get it to work.
This is the relevant part of the XAML
I'm using for the ComboBox
:
<UserControl.Resources>
<status:FlightLevelConverter x:Key="FlightLevelConverter"/>
</UserControl.Resources>
...
<ComboBox x:Name="AltitudeCombo" Grid.Row="0" Grid.Column="3" Width="100">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FlightLevelConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
It displays the un-converted numeric values, not the nice string values. I get no errors and if I set a breakpoint in the converter it doesn't get hit, showing that the converter is never called.
I've spent all morning trawling the Internet in general and StackOverflow in particular to try to discover what I'm doing wrong, but haven't found out anything useful.
Why is my converter not being called? What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如何将项目添加到组合框?
您应该将 ItemsSource 属性设置为数值的集合,例如,
如果您像这样添加 ComboBoxItems
,则不会应用 ItemTemplate,因此不会应用与其转换器的绑定。
How do you add the items to the ComboBox?
You should set the ItemsSource property to a collection of numeric values, e.g.
If you add ComboBoxItems like this
the ItemTemplate and hence the binding with its converter won't be applied.
这是一个简短的工作示例。您可以比较代码...
XAML:
C#:
Here is a short working sample. You can compare code...
XAML:
C#:
如果 ComboBox.IsEditable == true,则 ComboBox.ItemTemplate 不适用于 ComboBox 的主要部分。它仅适用于下拉列表条目。尝试设置 ComboBox.IsEditable == false。这可能有帮助。
ComboBox.ItemTemplate is not applicable to the main part of the ComboBox if ComboBox.IsEditable == true. It works for dropdown list entries only. Try to set ComboBox.IsEditable == false. It might help.