开发者

How do you replace an entire xaml element?

<ListView>
    <ListView.Res开发者_如何学Pythonources>
        <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>

On the marketed line, I'm replacing the contents of a UserControl with the contents of another UserControl that is dynamically created in code. I'd like to replace the entire control, and not just the content. Is there a way to do this?

Edit:

To clarify my intent, the Items that my ListView collection holds owns a Control (which inherits from UserControl) that knows how to manipulate the item's value. Simply binding the Content gets me the visual representation, but discards other non-content related properties of the derived Control. If I could replace that UserControl in my template in a more whole-sale fashion, this would fix that problem.


I finally figured this one out:

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

The ContentPresenter is exactly what I was looking for.


Looks like you want to switch between label and textbox in a cell based on some state. I'd use trigger for that.

Or see if this might be of use: http://www.codeproject.com/KB/WPF/editabletextblock.aspx


Updated:

Here's a hack (I don't recommend this and I hate myself a little for posting it):

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

In code behind:

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

Obviously, you'll need to store the reference to the border and keep track of which border belongs to which cell. I can't imagine this is less complex than switching templates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜