![](/img/trans.png)
[英]Set IsEnabled for nested LayoutGroup based on property of parent
[英]Set IsEnabled Property of ComboBox Based on SelectedItem
我想基於是否在另一個ComboBox中選擇了一個項目來啟用/禁用ComboBox。 我可以通過在“樣式”上設置觸發器來使其正常工作,但這會覆蓋我的組合框自定義全局樣式。 還有另一種方法可以在不失去風格的情況下獲得相同的功能嗎?
<ComboBox Grid.Column="1" Grid.Row="1"
Name="AnalysisComboBox"
MinWidth="200"
VerticalAlignment="Center" HorizontalAlignment="Left"
ItemsSource="{Binding Path=AvailableAnalysis}">
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem,ElementName=ApplicationComboBox}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
您不需要通過樣式來執行此操作,可以使用值轉換器直接綁定IsEnabled屬性,如下所示:
<ComboBox Grid.Column="1" Grid.Row="1"
Name="AnalysisComboBox"
MinWidth="200"
VerticalAlignment="Center" HorizontalAlignment="Left"
IsEnabled={Binding SelectedItem, ElementName=ApplicationComboBox, Converter={StaticResource NullToFalseConverter}}"
ItemsSource="{Binding Path=AvailableAnalysis}"/>
其中NullToFalseConverter是以下轉換器的實例的鍵:
public class NullToFalseConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value == null;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
是的,您可以將BasedOn
屬性設置為“繼承”全局樣式:
<ComboBox Grid.Column="1" Grid.Row="1"
Name="AnalysisComboBox"
MinWidth="200"
VerticalAlignment="Center" HorizontalAlignment="Left"
ItemsSource="{Binding Path=AvailableAnalysis}">
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}"
BasedOn="{StaticResource {x:Type ComboBox}}">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem,ElementName=ApplicationComboBox}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
您可以設置全局樣式的鍵(如果它不是隱式的),而不是{StaticResource {x:Type ComboBox}}
。
但是對於此特定任務,您無需定義樣式。 您只需將綁定設置為IsEnabled屬性,然后使用轉換器將另一個組合框的選定項轉換為布爾值:
<ComboBox Grid.Column="1" Grid.Row="1"
Name="AnalysisComboBox"
MinWidth="200"
VerticalAlignment="Center" HorizontalAlignment="Left"
ItemsSource="{Binding Path=AvailableAnalysis}"
IsEnabled="{Binding SelectedItem,ElementName=ApplicationComboBox, Converter={StaticResource NotNullConverter}"/>
您可以簡單地進行“常規”綁定,並使用一個值轉換器來更改“值存在” => true,“值為空” => false。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.