【发布时间】:2016-02-18 22:29:32
【问题描述】:
项目类型: .NET 4.0 WPF 桌面应用程序
您好。
我目前正在研究一种解决方案,以在 WPF 应用程序中利用 IMultiValueConverters 将两个 ComboBox 的 SelectedItem 属性绑定到按钮的 IsEnabled 属性。组合框被放置在单独的用户控件中,这些用户控件与按钮本身一起嵌套在主窗口中。
MainWindow.xaml
<Window>
<Window.Resources>
<local:MultiNullToBoolConverter x:Key="MultiNullToBoolConverter" />
</Window.Resources>
<Grid>
<local:ucDatabaseSelection x:Name="ucSourceDatabase" />
<local:ucDatabaseSelection x:Name="ucTargetDatabase" />
<Button x:Name="btnContinue">
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource MultiNullToBoolConverter}">
<Binding ElementName="ucSourceDatabase" Path="cbxServerDatabaseCollection.SelectedItem" />
<Binding ElementName="ucTargetDatabase" Path="cbxServerDatabaseCollection.SelectedItem" />
</MultiBinding>
</Button.IsEnabled>
</Button>
</Grid>
</Window>
ucDatabaseSelection.xaml
<UserControl>
<ComboBox x:Name="cbxServerDatabaseCollection">
<ComboBoxItem Content="Server A" />
<ComboBoxItem Content="Server B" />
</ComboBox>
</UserControl>
MultiNullToBoolConverter.cs
/// <summary>
/// Converts two objects (values[0] and values[1]) to boolean
/// </summary>
/// <returns>TRUE if both objects are not null; FALSE if at least one object is null</returns>
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[0] != null && values[1] != null) return true;
else return false;
}
只有当两个 ComboBox 的 SelectedItem 属性不为空时,Button 的 IsEnabled 属性才应为真。
我现在遇到的问题是我无法让绑定从 MainWindow 按钮通过 UserControls 并到 ComboBoxes 上工作。我在这里错过了 UpdateTriggers 还是根本不可能在不使用 UserControl 类中的 DependencyProperties 的情况下直接绑定它?
【问题讨论】:
-
WPF 数据绑定仅适用于公共属性。因此,UserControl 需要有一个返回
cbxServerDatabaseCollection字段值的公共属性,或者直接返回其 ComboBox 的SelectedItem的属性。 -
然后您可以使用 LINQ 简化转换器的代码,方法是编写
return values.All(v => v != null); -
谢谢你,克莱门斯!设置引用
cbxServerDatabaseCollection的公共属性完全符合预期。有没有办法将您的评论标记为答案?
标签: c# wpf xaml user-controls imultivalueconverter