切换组合框绑定到属性不起作用

时间:2014-08-11 13:37:01

标签: c# wpf mvvm combobox

我有两个组合框,当第一个被选中时,第二个应该是活动的(IsEnabled = true)。请查看以下代码段

<UserControl x:Class="RestoreComputer.Views.ConfigView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="20,0,0,0" Height="50">
            <ComboBox Name="_server" ItemsSource="{Binding Path=Servers}" SelectedItem="{Binding Path=Server}" IsSynchronizedWithCurrentItem="True" Width="100"  VerticalContentAlignment="Center" Text="18"/>
            <Image Source="../Images/narrow.png" Margin="10,0,10,0"/>
            <ComboBox Name="_computer" IsEnabled="{Binding Path=ComputerPredicate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True">
                Hello1
            </ComboBox>
        </StackPanel>
    </Grid>
</UserControl> 

如您所见,我将IsEnabled属性绑定到类似MVVM样式的属性。选择_server组合框后,应启用_computer组合框。

属性更改了代码段。

public bool ComputerPredicate
{

    get { return _computerPredicate; }
    set
    {
        if (value != _computerPredicate)
        {
            _computerPredicate = value;
            RaisePropertyChanged(ref _computerPredicate, value, () => ComputerPredicate);
        }
    }
}

public string Server
{
    get { return _server; }
    set
    {
        if (value != _server)
        {
            _server = value;
            ComputerPredicate = true;
            RaisePropertyChanged(ref _server, value, () => Server);
        }
    }
}

第一个被选中时,如何在第二个组合框中启用组合框?

1 个答案:

答案 0 :(得分:1)

您可以直接在XAML中执行此操作。如果我找到你你想要禁用_computer comboBox,以防_server comboBox 的所选项为null。

您可以使用简单的 DataTrigger 来实现这一目标:

<ComboBox x:Name="_server"/>
<ComboBox x:Name="_computer">
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItem,
                                               ElementName=_server}"
                             Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>
相关问题