【问题标题】:How do you replace an entire xaml element?如何替换整个 xaml 元素?
【发布时间】:2010-03-20 18:46:49
【问题描述】:
<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 的内容。 我想替换整个控件,而不仅仅是内容。有没有办法做到这一点?

编辑:

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

【问题讨论】:

    标签: wpf xaml user-controls


    【解决方案1】:

    我终于想通了:

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

    ContentPresenter 正是我想要的。

    【讨论】:

      【解决方案2】:

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

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


      更新:

      这是一个 hack(我不推荐这个,我有点讨厌自己发布它):

          <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;
          }
      

      显然,您需要存储对边框的引用并跟踪哪个边框属于哪个单元格。我无法想象这比切换模板更简单。

      【讨论】:

      • 有趣的链接,但这不是我想要实现的。我想用另一个任意的 UserControl 替换那个 UserControl。
      • 在这种情况下是否可以即时切换模板?有关详细信息,请参阅此处codingbandit.com/Blog/blog/…。有一种方法可以做你想做的事,但它很笨拙,我怀疑不是实现所需行为的最佳方法。
      • 动态切换模板是我最初所做的。切换 UserControl 大大简化了我的工作。
      猜你喜欢
      • 2021-11-13
      • 2021-11-14
      • 2021-05-02
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多