WPF 绑定到列表框 selectedItem [英] WPF binding to Listbox selectedItem

查看:44
本文介绍了WPF 绑定到列表框 selectedItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助解决以下问题 - 一直在玩这个,但我一生都无法让它工作.

Can anyone help with the following - been playing about with this but can't for the life of me get it to work.

我有一个包含以下属性的视图模型;

I've got a view model which contains the following properties;

public ObservableCollection<Rule> Rules { get; set; }
public Rule SelectedRule { get; set; }

在我的 XAML 中;

In my XAML I've got;

<ListBox x:Name="lbRules" ItemsSource="{Binding Path=Rules}" 
         SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
    <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Name:" />
                <TextBox x:Name="ruleName">
                    <TextBox.Text>
                        <Binding Path="Name" UpdateSourceTrigger="PropertyChanged" />
                    </TextBox.Text>
                </TextBox>
            </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

现在 ItemsSource 工作正常,我得到了一个 Rule 对象列表,它们的名称显示在 lbRules 中.

Now the ItemsSource works fine and I get a list of Rule objects with their names displayed in lbRules.

我遇到的问题是将 SelectedRule 属性绑定到 lbRules 的 SelectedItem.我尝试将文本块的文本属性绑定到 SelectedRule,但它始终为 null.

Trouble I am having is binding the SelectedRule property to lbRules' SelectedItem. I tried binding a textblock's text property to SelectedRule but it is always null.

<TextBlock Text="{Binding Path=SelectedRule.Name}" />

我在输出窗口中看到的错误是:BindingExpression 路径错误:找不到SelectedRule"属性.

The error I'm seeing in the output window is: BindingExpression path error: 'SelectedRule' property not found.

任何人都可以帮助我进行此绑定 - 我不明白为什么它不应该找到 SelectedRule 属性.

Can anyone help me with this binding - I can't see why it shouldn't find the SelectedRule property.

然后我尝试将文本块的文本属性更改为波纹管,这很有效.问题是我想在我的 ViewModel 中使用 SelectedRule.

I then tried changing the textblock's text property as bellow, which works. Trouble is I want to use the SelectedRule in my ViewModel.

<TextBlock Text="{Binding ElementName=lbRules, Path=SelectedItem.Name}" />

非常感谢您的帮助.

推荐答案

首先,您需要在您的视图模型中实现 INotifyPropertyChanged 接口并在其中引发 PropertyChanged 事件Rule 属性的设置器.否则,绑定到 SelectedRule 属性的任何控件都不会知道"它何时被更改.

First off, you need to implement INotifyPropertyChanged interface in your view model and raise the PropertyChanged event in the setter of the Rule property. Otherwise no control that binds to the SelectedRule property will "know" when it has been changed.

然后,您的 XAML

<TextBlock Text="{Binding Path=SelectedRule.Name}" />

如果此 TextBlock 位于 ListBoxItemTemplate 之外并且具有相同的 DataContext,则

是完全有效的ListBox.

is perfectly valid if this TextBlock is outside the ListBox's ItemTemplate and has the same DataContext as the ListBox.

这篇关于WPF 绑定到列表框 selectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆