Using bindings in DataTrigger condition

前端 未结 1 453
旧巷少年郎
旧巷少年郎 2020-12-14 09:03

Let\'s say I have the following simple classes:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class P         


        
相关标签:
1条回答
  • 2020-12-14 09:38

    You can't use a binding on the Value property, but you can get around this by using a MultiBinding and an IMultiValueConverter. I would define my Trigger in a Style in e.g. the Window.Resources, which would give something like this:

    <Window.Resources>
        <local:SomeMultiConverter x:Key="someMultiConverter" />
        <Style x:Key="someStyle" TargetType="StackPanel">
            <Setter Property="StackPanel.Background" Value="Red" />
            <Style.Triggers>
                <DataTrigger Value="True">
                    <DataTrigger.Binding>
                        <MultiBinding Converter="{StaticResource someMultiConverter}">
                            <Binding Path="Id"></Binding>
                            <Binding ElementName="Foo" Path="DataContext.ActiveId"></Binding>
                        </MultiBinding>
                    </DataTrigger.Binding>
                    <Setter Property="StackPanel.Background" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style> 
    </Window.Resources>
    <Grid x:Name="Foo">
        <StackPanel DataContext="{Binding CurrentPerson}" Style="{StaticResource someStyle}" >
            <TextBlock Text="{Binding Id}" />
            <TextBlock Text="{Binding Name}" />
        </StackPanel>
    </Grid>
    

    See this link for an example on MultiBinding and IMultiValueConverter. They're fairly easy to write.

    0 讨论(0)
提交回复
热议问题