数据触发器集模板



我必须设置模板,我使用了DataTrigger,但它不起作用。

我的代码 :

<Style TargetType="{x:Type local:My_type}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding GUID, RelativeSource={RelativeSource AncestorType={x:Type local:MyClassViewControl}}}" 
                     Value="id1">
                <Setter Property="Template" Value="{StaticResource FirstTemplate}" />
        </DataTrigger>
        <DataTrigger Binding="{Binding GUID, 
                RelativeSource={RelativeSource AncestorType={x:Type local:MyClassViewControl}}}" 
                     Value="id2">
            <Setter Property="Template" Value="{StaticResource SecondTemplate}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

下面是一个示例。为什么我的代码不起作用?GUID 没有错("id1"或"id2")

我认为这是

"{Binding GUID, RelativeSource={RelativeSource 
      AncestorType={x:Type local:MyClassViewControl}}}"

应该是

"{Binding GUID, RelativeSource={RelativeSource FindAncestor, 
      AncestorType={x:Type local:MyClassViewControl}}}"

我找到了解决方案:在 C# 中创建模板选择器:

public class GUIDTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        FrameworkElement element = container as FrameworkElement;
        if (item != null && element != null)
        {
            string GUID = item as string;
            if (GUID != null)
            {
                if (GUID.Equals("id1"))
                {
                    return element.FindResource("FirstTemplate") as DataTemplate;
                }
                if (GUID.Equals("id2"))
                {
                    return element.FindResource("SecondTemplate") as DataTemplate;
                }
            }
        }
        return null;
    }
}

在我的 XAML 文件中:

<local:GUIDTemplateSelector x:Key="TheGUIDControlTemplateSelector"/>
<Style TargetType="{x:Type My_type}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:My_type}">
                <ContentControl ContentTemplateSelector="{StaticResource TheGUIDTemplateSelector}" Content="{Binding GUID,RelativeSource={RelativeSource AncestorType={x:Type local:My_type}}}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

相关内容

  • 没有找到相关文章

最新更新