xaml 选定项中的数据绑定
本文关键字:数据绑定 xaml | 更新日期: 2023-09-27 18:31:44
请看这个:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{StaticResource vm}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="194*"/>
<ColumnDefinition Width="489*"/>
</Grid.ColumnDefinitions>
<ListView HorizontalAlignment="Left"
ItemsSource="{Binding Path=Places}"
SelectedItem="{Binding Path=SelectedPlace, Mode=TwoWay}" Margin="0,96,0,0">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Title}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Grid.Column="0" HorizontalAlignment="Left">
<TextBlock
VerticalAlignment="Top"
Text="{Binding SelectedPlace.Title}" Margin="0,64,0,0"/>
</StackPanel>
</Grid>
我正在传入地点列表,它工作正常,列表显示在视图中。问题是selectedItem
.智能感知在这里找到属性
Text="{Binding SelectedPlace.Title}"
但它不会显示在视图中。当我在视图模型中放置断点时,我可以看到该值发生了变化:
public class MainViewModel : ViewModelBase
{
public ObservableCollection<Place> Places { get; set; }
public Place _selectedPlace { get; set; }
public Place SelectedPlace
{
get { return _selectedPlace; }
set { _selectedPlace = value; }
}
public MainViewModel()
{
Places = new ObservableCollection<Place>()
{
new Place() {Title = "London", Description = "London is a nice..."},
new Place() {Title = "Dublin", Description = "Dublin is a ...."}
};
}
}
有谁知道我错过了什么?谢谢
你需要调用 RaisePropertyChanged。
public Place SelectedPlace
{
get { return _selectedPlace; }
set
{ _selectedPlace = value;
RaisePropertyChanged("SelectedPlace")}
}
}
您可能还应该初始化此属性:
public MainViewModel()
{
Places = new ObservableCollection<Place>()
{
new Place() {Title = "London", Description = "London is a nice..."},
new Place() {Title = "Dublin", Description = "Dublin is a ...."}
};
SelectedPlace = Places[0];
}
并通过使 SelectedPlace 属性的支持字段成为私有字段来帮自己一个忙。您可能希望将其更改为:
public Place _selectedPlace { get; set; }
自
private Place _selectedPlace;