【问题标题】:How to bind selected Item from ListBox to ComboBox如何将所选项目从 ListBox 绑定到 ComboBox
【发布时间】:2021-01-23 23:44:48
【问题描述】:

我有一个ListBox,项目是动态生成的。我还有一个ComboBox。

每个项目都有一个名为“名称”的string 属性。

当我在ListBox 上选择此项目时,我想将ComboBox 的默认值或文本设置为ListBox 中所选项目的“名称”。

我可以将它与“TextBlock”的“Text”属性绑定。但我无法使用ComboBox

这是我的代码:

XAML

<ListBox Name="MyList" ItemsSource="{Binding SourceList}"
         SelectedItem="{Binding SelectedObject, Mode=TwoWay}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Width="{Binding ElementName=MyList, Path=ActualWidth}"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border>
                <StackPanel>                   
                    <Grid>
                        <StackPanel>
                            <TextBlock {Binding Path=FileName}" />    
                            <TextBlock>
                                <Run Text="{Binding Name}" />
                            </TextBlock> 
                        </StackPanel>
                    </Grid>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我可以绑定这个TextBlock:

<TextBlock>
   <Run Text="{Binding SelectedItem.Name, ElementName=MyList}"/>
</TextBlock>

但它不适用于ComboBox:

<ComboBox ItemsSource="{Binding ElementName=MyList, Path=SelectedItem}" SelectedItem="{Binding SelectedObject}" Text="{Binding Name}">                             
</ComboBox>

【问题讨论】:

  • ComboBox.ItemsSource 是用于填充组合框项目的枚举。 SelectedItem 可能不是可枚举的,或者?

标签: c# .net wpf combobox binding


【解决方案1】:

您将ComboBox 上的ItemsSource 属性设置为ListBox 中的SelectedItem。这不起作用,因为绑定项目源必须是集合,在您的情况下它是单个非集合项目。

假设您已将ItemsSource 绑定到一个集合,例如SourceList。然后你可以使用DisplayMemberPath属性在ComboBox中指定应该用作标签的属性,这里是Name。

<ComboBox ItemsSource="{Binding SourceList}"
          SelectedItem="{Binding SelectedItem, ElementName=MyList}"
          DisplayMemberPath="Name">

如果要设置默认值,可以使用Text属性,但也必须将IsEditable属性设置为true,否则会被忽略。来自documentation:

当 IsEditable 属性为 true 时,设置此属性会将输入的初始文本放置在文本框中。当 IsEditable 为 false 时,设置该值无效。

这样做的缺点是会有一个默认文本,但可以编辑 ComboBox 值。

<ComboBox ItemsSource="{Binding SourceList}"
          SelectedItem="{Binding SelectedItem, ElementName=MyList}"
          DisplayMemberPath="Name"
          IsEditable="True">

如果您的要求存在编辑问题,您可以查看此related question。有一些变通方法,但它们非常复杂并且也有一些缺点。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多