首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在DataTemplate.Triggers中设置DataTemplate.VisualTree

在DataTemplate.Triggers中设置DataTemplate.VisualTree
EN

Stack Overflow用户
提问于 2012-07-17 03:35:40
回答 1查看 2.8K关注 0票数 2

大家好,我正试图在我的dataGrid中更改列的模板,但是我找不到在XAML中这样做的方法。我正试着用这种方式来做

代码语言:javascript
复制
<DataTemplate>
    <DataTemplate.Triggers>
        <Trigger Property="{Binding ElementName=isComboBox, Path=IsChecked}"
                 Value="True">
            <Setter Property="VisualTree">
                <Setter.Value>
                    <ComboBox ItemsSource="{Binding elementos}"/>                
                </Setter.Value>
            </Setter>
        </Trigger>
    </DataTemplate.Triggers>
</DataTemplate>

但是一个错误告诉我,The property VisualTree cannot be set as a property element on template. Only Triggers and Storyboards are allowed as property elements知道根据另一个控件改变DataGridCell中模板的不同方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-17 03:59:12

您不能在模板中更改模板,这不是它的工作方式。

有许多方法可以做到这一点。取决于应用程序的配置方式。最常用的方法是

绑定到property/collection

  • The集合的
  1. ContentControl或ItemsControl包含一个或多个不同类型的实例
  2. 您在应用程序资源中定义的DataTemplates具有与您的实例类型相匹配的DataType

例如,您的应用程序中有几个模型

代码语言:javascript
复制
public sealed class Foo
{
    public string Text {get;set;}
}

public sealed class Bar
{
    public bool Checked {get;set;}
}

您的应用程序公开一个包含一个或多个此类实例的属性

代码语言:javascript
复制
public partial class MainWindow : Window
{
    //INotifyPropertyChanged/DependencyObject stuff left out!
    public object FooOrBar {get;set;} 

    //snip
}

在XAML中,有一个扩展ItemsControlContentControl或类似类型的UIElement类型,可以绑定到该属性。

代码语言:javascript
复制
<Window 
    x:Name="root"
    xmlns:t="clr-namespace:MyApplicationWhereFooAndBarLive"
    SkipAllThatXmlnsDefinitionNonsenseForSpaceSavingsInThisExample="true"/>  
    <!-- see Resources below --> 
    <ConentControl Content="{Binding FooOrBar, ElementName=root}" />
</Window>

最后,在应用程序的资源中为每个类型定义DataTemplates

代码语言:javascript
复制
<Window.Resources>
    <DataTemplate DataType="{x:Type t:Foo}">
        <TextBox Text="{Binding Text}" />
    </DataTemplate >
    <DataTemplate DataType="{x:Type t:Bar}">
        <CheckBox Checked="{Binding Checked}" />
    </DataTemplate >
</Window.Resources>

DataTemplate选择的过程如下所示:

FooOrBar = new Foo();

  • The ContentControl的内容绑定更新(通过INPC或DependencyProperty)

  • The

  • 查找它的ContentControl,找到没有配置的DataTemplateSelector,并使用默认的DependencyProperty)

  • The默认DataTemplateSelector获取绑定到Content property.

  • The的对象的类型DataTemplateSelector (本质上)查找logical tree,该资源是DataTemplate并且具有与步骤4中标识的实例类型匹配的类型的键。

  • DataTemplate is DataTemplateSelector,并被传递给ConentControl

  • The树,并通过LoadContent()方法在其中加载视觉树。

  • ContentControl将此视觉树的根的DataContext设置为Content属性中的值(在我们的示例中,Foo)

  • This视觉树的新实例被添加为ConentControl的子级,并且现在在UI中可见。

ItemsControl的情况大致相同,只是添加了一个中介(即ListBox使用ListBoxItem作为中介,而LBI是一个ContentControl)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11511285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档