基于DataContext类型添加行为或样式

时间:2015-02-17 05:30:08

标签: c# wpf mvvm prism caliburn.micro

我需要根据元素的DataContext / Binding的类型而不是FrameworkElement本身的类型来应用Behavior / Style -

我正在寻找的东西相当于 -

<Style TargetType={typeof(DataContext) is SomeSelectableType}>
    <Setter Property="cal:Message.Attach" Value="[Event PreviewMouseLeftButtonDown]=[Action OnSelect]"/>
</Style>

OR

<Style TargetType={typeof(DataContext) is SelectableObject}>
    <DataTrigger Binding="IsSelected" Value="True">
        <Setter Property="BorderBrush" Value="Red"/>
    </DataTrigger>
</Style>

1 个答案:

答案 0 :(得分:3)

您可以根据FrameworkElement应用样式,但可以根据DataContext的类型限制触发器。

然后在触发器中,您可以根据类型设置适当的属性。

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button IsEnabled="False">
            <Button.Style>
                <Style TargetType="Button">
                    <Style.Triggers>

                        <DataTrigger Binding="{Binding Converter={StaticResource InstanceTypeConverter}}" Value="{x:Type local:ViewModel1}">
                            <Setter Property="Content" Value="ViewModel1"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Converter={StaticResource InstanceTypeConverter}}" Value="{x:Type local:ViewModel2}">
                            <Setter Property="Content" Value="ViewModel2"></Setter>
                        </DataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding Converter={StaticResource InstanceTypeConverter}}" Value="{x:Type local:ViewModel2}"></Condition>
                                <Condition Binding="{Binding IsEnabled,RelativeSource={RelativeSource Self}}" Value="False"></Condition>
                            </MultiDataTrigger.Conditions>
                            <MultiDataTrigger.Setters>
                                <Setter Property="Content" Value="ViewModel2 And Not Enabled"></Setter>
                            </MultiDataTrigger.Setters>
                        </MultiDataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </Grid>
</Window>

将实例转换为其类型

public  class InstanceTypeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value !=null ? value.GetType() : null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }