0

C# と MVVM は比較的新しいですが、MVVM Light Toolkit を使用して WP7 アプリを作成しています。ListBox 内のプロパティの双方向バインディングに問題があります。クライアントの ObservableCollection があり、個々のクライアントを選択しようとしています (クリックすると、新しい ViewModel が表示されます)。

選択した項目をクリックすると、SelectedItem プロパティが更新され、クリックされたクライアントに値が設定されます。ただし、クリックしてもセッターに到達しません(*でブレークポイントをマークしました)。私がどこで間違ったのか、またはより良い提案された解決策があることを誰かが知っていますか? 私はこの場所を何時間もトロールしてきました!

XAML マークアップ:

        <ListBox SelectedItem="{Binding SelectedItem, Mode=TwoWay}" ItemsSource="{Binding ClientList, Mode=TwoWay}" x:Name="FirstListBox" Margin="0,0,-12,0" ScrollViewer.VerticalScrollBarVisibility="Auto">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,0,0,17" Width="432">
                    <Button CommandParameter="{Binding}">
                        <helper:BindingHelper.Binding>
                            <helper:RelativeSourceBinding Path="ShowClientCommand" TargetProperty="Command"
                                    RelativeMode="ParentDataContext" />
                        </helper:BindingHelper.Binding>
                        <Button.Template>
                            <ControlTemplate>
                                <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

ビューモデルのプロパティ:

    public ObservableCollection<Client> ClientList
    {
        get 
        {
            return _clientList;
        }
        set 
        {
            _clientList = value;
            RaisePropertyChanged("ClientList");
        }
    }

    public Client SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
         *   _selectedItem = value;
            RaisePropertyChanged("SelectedItem");
        }
    }
4

1 に答える 1

0

selection_changed イベントにサインアップしていないため、プロパティが変更されていない可能性がありますか?

なぜそれが機能しないのか完全にはわかりませんが、私が常に使用し、テンプレートが推奨するソリューションを次に示します。

次のように、SelectionChanged イベントのリストボックスにサインアップします。

<ListBox SelectionChanged="FirstListBox_SelectionChanged" ItemsSource="{Binding ClientList, Mode=TwoWay}" x:Name="FirstListBox" Margin="0,0,-12,0" ScrollViewer.VerticalScrollBarVisibility="Auto">

次に、対応する .cs ファイルに、次のようなハンドラーを含めます。

private void FirstListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // If selected index is -1 (no selection) do nothing
    if (FirstListBox.SelectedIndex == -1)
        return;

    // get the client that's selected
    Client client = (Client) FirstListBox.selectedItem;

    //... do stuff with the client ....

    // reset the index (note this will fire this event again, but
    // it'll automatically return because of the first line
    FirstListBox.SelectedIndex = -1;
}
于 2012-03-15T23:48:23.163 に答える