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

查看:340
本文介绍了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的正常工作,我得到规则的列表,在lbRules显示其名称的对象。

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

麻烦我有是有约束力的SelectedRule属性lbRules的SelectedItem。我试着结合一个文本块的文本属性SelectedRule但它始终是空。

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}" />

我看到在输出窗口的错误是:
BindingEx pression路径错误:'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.

然后我试图改变文本块的文本属性为波纹管,它的工作原理。麻烦的是我想用SelectedRule在我的ViewModel。

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}" />

非常感谢您的帮助。

Thanks very much for your help.

推荐答案

首先,你需要实施 INotifyPropertyChanged的接口视图模型和提高的PropertyChanged 事件在规则 setter方法​​。否则,没有绑定到 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 超出了的ListBox 的ItemTemplate ,并且具有相同的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天全站免登陆