且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 绑定到列表框 selectedItem

更新时间:2022-06-03 03:20:57

首先,您需要在您的视图模型中实现 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.