将 WPF ComboBox 绑定到 ListBox DataTemplate 中的不同 ItemsSource

发布于 2024-08-30 15:49:15 字数 901 浏览 1 评论 0原文

我有一个列表框,其数据模板中包含一个文本框和一个组合框:

<ListBox Height="147" Margin="158,29,170,0" Name="PitcherListBox" VerticalAlignment="Top" ItemsSource="{Binding SomeCollectionOfObjects}" Background="Black">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBox Text="{Binding Path=Name}" />
                    <ComboBox ItemsSource="{Binding LocalArrayOfIntsProperty}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我想将列表框绑定到对象集合(我已成功完成),但我希望上述数据模板中的组合框将其 itemssource 设置为窗口上的本地属性(整数数组)。我仍然希望组合框在其所选项目和对象集合上的属性之间具有双向绑定...

我的代码如下: PitcherListBox.DataContext = this;

基本上最后,我希望列表框中的组合框具有与列表框本身不同的项目源。我似乎无法弄清楚如何在 XAML 中更改 ComboBox 的 ItemsSource。有人可以给我一些反馈吗?谢谢!

I have a ListBox that contains a textbox and a combobox in its datatemplate:

<ListBox Height="147" Margin="158,29,170,0" Name="PitcherListBox" VerticalAlignment="Top" ItemsSource="{Binding SomeCollectionOfObjects}" Background="Black">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBox Text="{Binding Path=Name}" />
                    <ComboBox ItemsSource="{Binding LocalArrayOfIntsProperty}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

I want to bind the listbox to a collection of objects (which I've done successfully), but I want the combobox in the above datatemplate to have its itemssource set to a local property on the window (array of ints). I still want the combobox to have a two-way bind between its selected item and a property on the collection of objects...

I have the following in code:
PitcherListBox.DataContext = this;

Basically in the end, I want the combobox within the listbox to have a different itemssource than the listbox itself. I can't seem to figure out how to change the ComboBox's ItemsSource in XAML. Can someone provide me some feedback? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我太投入 2024-09-06 15:49:15

试试这个:

<ComboBox ItemsSource="{Binding LocalArrayOfIntsProperty, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourWindowTypeHere}}}" />

请注意,您需要将 YourWindowTypeHere 替换为包含 LocalArrayOfIntsProperty 的窗口类型!另请记住,您需要为该类型定义一个 xml 命名空间!

Try this:

<ComboBox ItemsSource="{Binding LocalArrayOfIntsProperty, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourWindowTypeHere}}}" />

Note that you need to replace YourWindowTypeHere with the type of the Window containing the LocalArrayOfIntsProperty! Also remember that you will need to define an xml namespace for that type!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文