WPF:绑定到 ComboBox SelectedItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:23:45  来源:igfitidea点击:

WPF: Binding to ComboBox SelectedItem

wpfbindingcombobox

提问by user83493

I have a UserControl with ComboBox that based on XML data:

我有一个基于 XML 数据的带有 ComboBox 的 UserControl:

<Root>
<Node Background="Yellow" Foreground="Cyan" Image="1.ico" Property="aaaa" Value="28" />
<Node Background="SlateBlue" Foreground="Black" Image="2.ico" Property="bbbb" Value="2.5" />
<Node Background="Teal" Foreground="Green" Image="3.ico" Property="cccc" Value="4.0" />
<Node Background="Yellow" Foreground="Red" Image="4.ico" Property="dddd" Value="0" /></Root>

Here is the UserControl XAML:

这是用户控件 XAML:

<UserControl x:Class="xxxxxxxx.MyComboBox"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         x:Name="myComboBoxControl">
<UserControl.Resources>
    <DataTemplate x:Key="dataTemplateNode">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" MinWidth="20"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto" MinWidth="20"/>
            </Grid.ColumnDefinitions>
            <Border Background="{Binding XPath=@Background}" Grid.Column="0">
                <Image Source="{Binding XPath=@Image}" 
                       Width="16" 
                       Height="16" 
                       Margin="3" />
            </Border>
            <Border Background="{Binding XPath=@Background}" Grid.Column="1">
                <TextBlock Foreground="{Binding XPath=@Foreground}" 
                           Margin="3"
                           Text="{Binding XPath=@Property}" />
            </Border>
            <Border Background="{Binding XPath=@Background}" Grid.Column="2">
                <TextBlock Foreground="{Binding XPath=@Foreground}" 
                           Margin="3" 
                           FontWeight="Bold"
                           Text="{Binding XPath=@Value}" />
            </Border>
        </Grid>
    </DataTemplate>

    <XmlDataProvider x:Key="xmlNodeList" 
                     Source="/data/Combo.xml" 
                     XPath="/Root/Node"/>
</UserControl.Resources>

<ComboBox Name="myComboBox" 
          ItemsSource="{Binding Source={StaticResource xmlNodeList}}" 
          ItemTemplate="{StaticResource dataTemplateNode}"
          HorizontalContentAlignment="Stretch" /></UserControl>

In the MainForm.xaml I have a TextBox that I want to bind to the my UserControl SelectedItem.

在 MainForm.xaml 中,我有一个 TextBox,我想将它绑定到我的 UserControl SelectedItem。

<StackPanel Orientation="Horizontal">
<local:MyComboBox1 x:Name="comboBoxST" />
<TextBox x:Name="textBoxST"/></StackPanel>

I will glad if you will guid me how to do that.

如果你能指导我如何做到这一点,我会很高兴。

Thanks in advance!

提前致谢!

回答by Sergey Aldoukhov

The trick here is that when you have to bind to the SelectedItem on an ItemControl bound to XML, the selected item itself is an XmlElement, and you have to use XPath to get to the needed element/attribute.

这里的技巧是,当您必须绑定到绑定到 XML 的 ItemControl 上的 SelectedItem 时,所选项目本身就是一个 XmlElement,并且您必须使用 XPath 来获取所需的元素/属性。

The easiest way to achieve this is to use DataContext:

实现这一点的最简单方法是使用 DataContext:

<TextBox x:Name=textBoxST 
    DataContext="{Binding ElementName=comboBoxST, Path=SelectedItem}" 
    Text="{Binding XPath=@Value}"/>

回答by Bishop

For what it's worth, I preferred Sergey's earlier approach better. However, in my scenario, I had a label instead of a textbox but this worked for me:

就其价值而言,我更喜欢 Sergey 早期的方法。但是,在我的场景中,我有一个标签而不是文本框,但这对我有用:

    <Label x:Name="labelST" Content="{Binding ElementName=comboBoxST, Path=SelectedValue}"/>

Spaciba, Sergey.

斯帕西巴,谢尔盖。

回答by Sergey Aldoukhov

The answer posted above was for the case of a list box placed directly on the form. In case of UserControl and templated ComboBox, I would avoid pure xml binding - too many factors can break it. Instead, use this code to create a dependency property:

上面发布的答案是针对直接放置在表单上的列表框的情况。在 UserControl 和模板化 ComboBox 的情况下,我会避免纯 xml 绑定 - 太多因素会破坏它。相反,使用此代码创建依赖项属性:

  public MyComboBox()
    {
        InitializeComponent();
        myComboBox.SelectionChanged += MyComboBoxSelectionChanged;
    }

    void MyComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SetValue(SelValueProperty, ((XmlElement)e.AddedItems[0]).Attributes["Value"].Value);
    }

    public static readonly DependencyProperty SelValueProperty =
        DependencyProperty.Register("SelValue", typeof(string), typeof(MyComboBox),
            new FrameworkPropertyMetadata(""));

And binding is simple then:

然后绑定很简单:

<TextBox x:Name=textBoxST Text="{Binding ElementName=comboBoxST, Path=SelValue}"/>