XAML 不使用ItemSource时绑定到ComboBox SelectedValue

pn9klfpd  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(87)

我有一个问题,我有一个组合框,我想用来设置一个枚举的几个值之一,从枚举。
我希望我能像下面这样做。

<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding ParameterType}">
    <ComboBoxItem IsSelected="True" Tag="{x:Static model:ParameterType.AbsMachine}">
        <TextBlock Text="M" ToolTip="Relative to the machine zero" />
    </ComboBoxItem>
    <ComboBoxItem Tag="{x:Static model:ParameterType.AbsSample}">
        <TextBlock Text="S" ToolTip="Relative to sample zero"/>
    </ComboBoxItem>
    <ComboBoxItem Tag="{x:Static model:ParameterType.RelCurrent}">
        <TextBlock Text="R" ToolTip="Relative to current value"/>
    </ComboBoxItem>
</ComboBox>

然而,这似乎不起作用,使用snoop,我可以看到更改组合框设置了本地值,从SelectedValue中删除了绑定。
如果我做几乎相同的事情,但设置一个虚拟集合,我绑定itemsource到一切工作如预期。

<ComboBox SelectedValuePath="Value" ItemsSource="{Binding EndTypes, ElementName=RootControl}" SelectedValue="{Binding ParameterType}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="ParameterTypeWrapper">
            <TextBlock Text="{Binding Name}" ToolTip="{Binding ToolTip}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我真的不明白为什么用XAML定义的comboitems的方法不起作用,因为它似乎是这种情况下更整洁的解决方案,并且不会用额外的 Package 器类和列表污染后面的代码。
有人知道为什么除非使用ItemsSource,否则绑定到SelectedValue不起作用吗?

ewm0tg9j

ewm0tg9j1#

您可以使用SelectedItem代替。如果不使用ItemsSource,则它将是选定的ComboBoxItem。
所以,

<ComboBox SelectionChanged="OnSelectionChanged">

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) {
      var result = ((ComboBoxItem)comboBox.SelectedItem).Tag;
    }

不确定你是否可以在这里使用绑定。

相关问题