如何替换整个xaml元素?

时间:2010-03-20 18:46:49

标签: wpf xaml user-controls

<ListView>
    <ListView.Resources>
        <DataTempalte x:Key="label">
            <TextBlock Text="{Binding Label}"/>
        </DataTEmplate>
        <DataTemplate x:Key="editor">
            <UserControl Content="{Binding Control.content}"/> <!-- This is the line -->
        </DataTemplate>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name"  CellTemplate="{StaticResource label}"/>
            <GridViewColumn Header="Value" CellTemplate="{StaticResource editor}"/>
        </GridView>
    </ListView.View>

在市场上,我用UserControl的内容替换了在代码中动态创建的另一个UserControl的内容。 我想替换整个控件,而不仅仅是内容。有没有办法做到这一点?

编辑:

为了澄清我的意图,我的Items集合所拥有的ListView拥有一个知道如何操纵项目值的控件(继承自UserControl)。简单地绑定内容会获得可视化表示,但会丢弃派生控件的其他非内容相关属性。如果我能以更全面的方式替换模板中的UserControl,这将解决这个问题。

2 个答案:

答案 0 :(得分:2)

我终于想出了这个:

    <DataTemplate x:Key="editor">
        <ContentPresenter Content="{Binding Path=Control}"/>
    </DataTemplate>

ContentPresenter正是我所寻找的。

答案 1 :(得分:0)

看起来你想根据某种状态在单元格中的标签和文本框之间切换。我会使用触发器。

或者看看这是否有用:http://www.codeproject.com/KB/WPF/editabletextblock.aspx


更新:

这是一个黑客(我不推荐这个,我讨厌自己发布它):

    <DataTemplate x:Key="editor">
        <Border Loaded="Border_Loaded">
            <UserControl Content="{Binding Control.content}"/>
        </Border>
    </DataTemplate>

在代码背后:

    private void Border_Loaded(object sender, RoutedEventArgs e)
    {
        // Example of replacement
        Button b = new Button();
        b.Content = "Woot!";
        ((Border)sender).Child = b;
    }

显然,您需要将引用存储到边框并跟踪哪个边框属于哪个单元格。我无法想象这不如切换模板那么复杂。

相关问题