あなたはCheckBox.IsChecked
プロパティにごListBox.ItemsSource
プロパティをバインドし、状態を確認し、適切な項目を返すためにValueConveter
を使用することができます。
この例では、要素にバインドされたモデルからアイテムを選択するために、MultiValueConveter
を使用します。
:ItemSource
の通知を提供する方法の例が含まれています。 Window.Resources
で
宣言コンバータ:
<CheckBox Name="CheckBox" />
<ListBox>
<ListBox.ItemsSource>
<MultiBinding Converter="{StaticResource isCheckedConverter}">
<Binding ElementName="CheckBox" Path="IsChecked"/>
<Binding Path="MyModel.MyLists" RelativeSource="{RelativeSource AncestorType={x:Type Window}}" />
</MultiBinding>
</ListBox.ItemsSource>
</ListBox>
はWindow
作成:
:
public partial class MainWindow : Window
{
public MyModel MyModel { get; set; }
public MainWindow()
{
InitializeComponent();
MyModel = new MyModel();
}
}
は最速を作成
<Window.Resources>
<local:IsCheckedConverter x:Key="isCheckedConverter" />
</Window.Resources>
XAML
コードを作成します
public class IsCheckedConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isChecked = (bool)values[0];
List<string>[] lists = (List<string>[])values[1];
if (isChecked == true)
{
return lists[0];
}
else
{
return lists[1];
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
例モデルの実装:
public class MyModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List<string>[] MyLists { get; set; }
public MyModel()
{
MyLists = new List<string>[2];
MyLists[0] = new List<string>() { "abc", "def", "ghi" };
MyLists[1] = new List<string>() { "123", "456", "789" };
}
public void UpdateListsExample()
{
MyLists[0] = new List<string>() { "abc", "def", "ghi", "jkl" };
MyLists[1] = new List<string>() { "123", "456" };
NotifyPropertyChanged("MyLists");
}
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
@すべての回答:ありがとう、すべての答えのために!最後に、Krzysztof BrachaのMultipleBindingソリューションを使用して欲しいものを探し出しました。私は複数のバインディングブロック内にItemsSourceを配置し、チェックボックスの状態に応じて出力リストを設定するコンバータを使用します。シンプルで洗練されたソリューションを提供します(私にとって)。 –