0

を使用しておりListBox、 をクリックしたときに背景ウィンドウの色を変更したいのですがListBoxItem、メソッドは機能していますが、バインディングで同じことをしたいです。

<ListBox Grid.Column="1" Grid.Row="3" Grid.RowSpan="2" Margin="10,20,30,10" Name="listBox1" SelectionChanged="listBox1_SelectionChanged_1">
            <ListBoxItem Content="Blue" Name="lst" />
            <ListBoxItem Content="Green" Name="lst1" />
            <ListBoxItem Content="Yellow" Name="lst2"/>
            <ListBoxItem Content="Transparent" Name="lst3"/>


        </ListBox>

私は次の方法を使用しています:

private void listBox1_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {
       if(listBox1.SelectedIndex.ToString() == "0")
       {
            win.Background = Brushes.Blue;
       }
       else if (listBox1.SelectedIndex.ToString() == "1")
       {
           win.Background = Brushes.Green;
       }
       else if (listBox1.SelectedIndex.ToString() == "2")
       {
           win.Background = Brushes.Yellow;
       }
       else
       {
           win.Background = Brushes.Transparent;
       }


    }

しかし、バインド メソッドを使用する必要があります。

4

1 に答える 1

0

MVVM に従い、リストボックスの値 (基本的には色) をモデルから取得することで、これを非常に簡単に実現できます。その後、フォームの背景を同じ値にバインドできます。

したがって、基本的にモデルは次のようになります。

public class ColorModel
{
   public Enum Colors{get; set;}
}

public enum Colors
{
    Red,
    Blue,
    Green
}

Viewmodel はこれのコレクションを作成します。

そして、ビューはそれをリストボックスにバインドします。ウィンドウの背景の場合 - これをリストボックスの値にバインドし、コンバーターを使用して (モデルがこれを色として定義していないため)、色を変更できます。

完全に機能するサンプルが必要な場合は、お知らせください。私のデスクですぐに何かを投稿しようとします。

于 2012-10-03T15:48:45.263 に答える