多重绑定到IsEnable

Kei*_*son 9 wpf textbox contentcontrol isenabled

我需要绑定一个TextBox符合两个标准:

  • 如果Text.Length> 0,则为IsEnabled
  • IsEnabled if user.IsEnabled

user.IsEnabled从数据源中提取出来.我想知道是否有人有一个简单的方法来做到这一点.

这是XAML:

<ContentControl IsEnabled="{Binding Path=Enabled, Source={StaticResource UserInfo}}"> 
    <TextBox DataContext="{DynamicResource UserInfo}" Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding Path=Text, RelativeSource={RelativeSource Self}, Converter={StaticResource LengthToBool}}"/> 
</ContentControl>
Run Code Online (Sandbox Code Playgroud)

Pav*_*nin 7

正如GazTheDestroyer所说,你可以使用MultiBinding.

您还可以使用MultiDataTrigger使用仅限XAML的解决方案来实现此功能

但你应该切换条件因为触发器只支持相等

<Style.Triggers>  
  <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
          <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text.Length}" Value="0" />
          <Condition Binding="{Binding Source=... Path=IsEnabled}" Value="False" />
        </MultiDataTrigger.Conditions>
        <Setter Property="IsEnabled" Value="False" />
      </MultiDataTrigger>  
</Style.Triggers>
Run Code Online (Sandbox Code Playgroud)

如果不满足其中一个条件,则将值设置为其默认值或样式中的值.但是不要设置本地值,因为它会覆盖样式和触发器的值.


rrh*_*tjr 6

由于您只需要逻辑OR,因此每个属性只需要两个触发器.

试试这个XAML:

<StackPanel>
        <StackPanel.Resources>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=InputText, Path=Text}" Value="" >
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=MyIsEnabled}" Value="False" >
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </StackPanel.Resources>
        <StackPanel Orientation="Horizontal">
            <Label>MyIsEnabled</Label>
            <CheckBox IsChecked="{Binding Path=MyIsEnabled}" />
        </StackPanel>
        <TextBox Name="InputText">A block of text.</TextBox>
        <Button Name="TheButton" Content="A big button.">     
        </Button>
    </StackPanel>
Run Code Online (Sandbox Code Playgroud)

我设置DataContextWindow有一个DependencyProperty被调用的类MyIsEnabled.显然你必须修改你的特定DataContext.

这是相关的代码隐藏:

public bool MyIsEnabled
{
    get { return (bool)GetValue(IsEnabledProperty); }
    set { SetValue(IsEnabledProperty, value); }
}

public static readonly DependencyProperty MyIsEnabledProperty =
    DependencyProperty.Register("MyIsEnabled", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(true));


public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!