WPF绑定到列表框将selectedItem

编程入门 行业动态 更新时间:2024-10-20 21:01:30
本文介绍了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

本文发布于:2023-11-06 14:16:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   列表   WPF   selectedItem

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!