繁体   English   中英

如何将 ListBox 中的选定项绑定到 ComboBox

[英]How to bind selected Item from ListBox to ComboBox

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

每个项目都有一个名为“Name”的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属性设置为ListBoxSelectedItem 这不起作用,因为绑定项目源必须是一个集合,在您的情况下它是一个非集合项目。

让我们假设您已将ItemsSource绑定到一个集合,例如SourceList 然后,您可以使用DisplayMemberPath属性指定应用作ComboBox标签的属性,此处为Name

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

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

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

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

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

如果编辑与您的要求有关,您可以查看此相关问题 有一些解决方法,但它们非常复杂,并且也有一些缺点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM