如何将选定的项目从列表框绑定到组合框

时间:2020-10-08 21:22:09

标签: c# .net wpf combobox binding

我有一个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>

1 个答案:

答案 0 :(得分:1)

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

让我们假设您已将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。有一些解决方法,但是它们很复杂并且也有一些缺点。