在xaml SelectedItem中进行数据绑定

时间:2014-11-22 21:17:51

标签: c# xaml

请看一下:

<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。 intellisense在这里找到属性

 Text="{Binding SelectedPlace.Title}"

但它没有出现在视图中。 当我在viewmodel中放置一个断点时,我可以看到该值发生了变化:

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 ...."}
            };
        }
    }

有谁知道我错过了什么?感谢

1 个答案:

答案 0 :(得分:1)

您需要调用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;