我的視圖中有兩個組合框。WPF:根據另一個下拉列表上的值啓用下拉列表
我想要的是,當我在ComboBox1上選擇值1時,ComboBox2變爲啓用狀態。但是,當我在ComboBox1中選擇任何其他不是1的值時,ComboBox2保持禁用狀態。
我的視圖中有兩個組合框。WPF:根據另一個下拉列表上的值啓用下拉列表
我想要的是,當我在ComboBox1上選擇值1時,ComboBox2變爲啓用狀態。但是,當我在ComboBox1中選擇任何其他不是1的值時,ComboBox2保持禁用狀態。
您的XAML:
<ComboBox x:Name="cb1" Margin="10,0" IsReadOnly="True" IsEditable="True" Text="Please select" HorizontalAlignment="Center" >
<ComboBoxItem x:Name="cbi11" Content="Option1" HorizontalAlignment="Left" Width="198" Selected="cbi11_Selected" />
<ComboBoxItem x:Name="cbi12" Content="Option2" HorizontalAlignment="Left" Width="198" Selected="cbi12_Selected"/>
<ComboBoxItem x:Name="cbi13" Content="Option3" HorizontalAlignment="Left" Width="198" Selected="cbi13_Selected"/>
</ComboBox>
<ComboBox x:Name="cb2" Margin="10,0" IsReadOnly="True" IsEditable="True" Text="Please select" HorizontalAlignment="Center" >
<ComboBoxItem x:Name="cbi21" Content="Option1" HorizontalAlignment="Left" Width="198" Selected="cbi21_Selected" />
<ComboBoxItem x:Name="cbi22" Content="Option2" HorizontalAlignment="Left" Width="198" Selected="cbi22_Selected"/>
<ComboBoxItem x:Name="cbi23" Content="Option3" HorizontalAlignment="Left" Width="198" Selected="cbi23_Selected"/>
</ComboBox>
而且背後的代碼:
private void cbi11_Selected(object sender, RoutedEventArgs e)
{
cb2.IsEnabled = true;
}
private void cbi12_Selected(object sender, RoutedEventArgs e)
{
cb2.IsEnabled = false;
}
private void cbi13_Selected(object sender, RoutedEventArgs e)
{
cb2.IsEnabled = false;
}
如果你正確地這樣做,那麼你問錯了問題爲您的視圖模型將完成大部分的工作,爲你
假設你有一個這樣的視圖模型(使用Prism)
public class VM:BindableBase
{
public ICollectionView Combo1Options {get,set}
public ICollectionView Combo2Options {get,set}
private object _Combo1Value;
private object _Combo2Value;
public object Combo1Value
{
get { return _Combo1Value; }
set
{
if(SetProperty(ref _Combo1Value, value))
{
Combo2Options .Refresh();
PropertyChanged(nameof(Combo2Enabled));
}
}
}
public object Combo2Value
{
get { return _Combo2Value; }
set { SetProperty(ref _Combo2Value, value); }
}
public bool Combo2Enabled => Combo1Value != null;//or what ever logic defines if combo2 is required
}
那麼你就只綁定到視圖模型
<ComboBox ItemSource={Binding Combo1Options }, SelectedItem={Binding Combo1Value }/>
<ComboBox ItemSource={Binding Combo2Options }, SelectedItem={Binding Combo2Value } IsEnabled={Binding Combo2Enabled}/>
使用的CollectionView的你獲得過濾的組合框項目的能力,所以我會推薦它
@Timo Kiander是什麼你想做? – ChrisIo