在Windows Phone 8.1上使用MVVM Light进行双向数据绑定

时间:2016-02-01 18:34:48

标签: xaml mvvm windows-phone-8.1 windows-store-apps mvvm-light

我尝试使用MVVM创建一个带ListPickerFlyout的自定义按钮。我希望达到的结果是这样的:

custom Button with ListPickerFlyout

我的问题是如何将SelectedItemListPickerFlyout绑定到内容TextBlock

我正在使用MVVM Light Windows Phone 8.1(Store Appp)。

我的Xaml代码:

<Button Background="White"
    HorizontalAlignment="Stretch" 
    HorizontalContentAlignment="Stretch">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="40" />
    </Grid.ColumnDefinitions>

    <!-- Content TextBlock -->
    <TextBlock Text="{Binding MyVM.SelectedItem, Mode=TwoWay}"
                Style="{StaticResource DefaultTextBlock}"
                FontSize="22"
                HorizontalAlignment="Left"
                VerticalAlignment="Center"
                Margin="10, 0, 0, 0"/>

    <Image Height="20"  Grid.Column="1"
            VerticalAlignment="Center" HorizontalAlignment="Center"
            Source="../Assets/icons/arrow_down.png"/>
</Grid>

<Button.Flyout>
    <ListPickerFlyout PickerFlyoutBase.Title="$Items$"
                        ItemsSource="{Binding MyVM.listItems}"
                        SelectedItem="{Binding MyVM.SelectedItem, Mode=TwoWay}" >
        <ListPickerFlyout.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding}"
                                Style="{StaticResource DefaultTextBlock}"
                                FontSize="22"/>
                </StackPanel>
            </DataTemplate>
        </ListPickerFlyout.ItemTemplate>
    </ListPickerFlyout>
</Button.Flyout>

在MyVM中我有

public string SelectedItem { get; set; }

编辑:

解决了问题,我忘了添加RaisePropertyChanged("SelectedItem");

所以,在我的MVVM类中:

private string _selectedItem;
public string SelectedItem
{
    get { return _selectedItem; }
    set
    {
        if (_selectedItem != value)
        {
            _selectedItem = value;
            RaisePropertyChanged("SelectedItem");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

只需要在MVVM类中添加RaisePropertyChanged("SelectedItem");

完整的代码:

private string _selectedItem;
public string SelectedItem
{
    get { return _selectedItem; }
    set
    {
        if (_selectedItem != value)
        {
            _selectedItem = value;
            RaisePropertyChanged("SelectedItem");
        }
    }
}