0

我必须 SetTemplate 并且我使用了 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”)

4

2 回答 2

0

我认为这

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

应该

"{Binding GUID, RelativeSource={RelativeSource FindAncestor, 
      AncestorType={x:Type local:MyClassViewControl}}}"
于 2012-06-15T14:25:58.813 回答
0

我找到了解决方案:在 C# 中创建 TemplateSelector:

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>
于 2012-06-18T09:03:45.417 回答