【问题标题】:Code behind doesn't work as XAML后面的代码不能用作 XAML
【发布时间】:2013-06-25 05:04:00
【问题描述】:

我正在学习 WPF,但遇到了一些麻烦。我制作了这个 XAML:

<Window.Resources>
  <DataTemplate x:Key="TemplateTest">
    <Button Margin="10"
            BorderThickness="2"
            Content="{Binding Path=Text}">
      <Button.Effect>
        <DropShadowEffect BlurRadius="20" />
      </Button.Effect>
    </Button>
  </DataTemplate>
</Window.Resources>

<StackPanel x:Name="StackPanel">
  <TextBox x:Name="TextBox"
           Margin="10">TextBox</TextBox>

  <ContentControl Content="{Binding ElementName=TextBox, Path=.}"
                  ContentTemplate="{StaticResource ResourceKey=TemplateTest}" />
</StackPanel>

以及背后的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var Resource = this.Resources["TemplateTest"] as DataTemplate;

        StackPanel.Children.Add(
            new ContentControl()
            {
                Content = new Binding()
                {
                    ElementName = "TextBox",
                    Path = new PropertyPath(".")
                },

                ContentTemplate = Resource,
            });
    }
}

我的问题是文本框的文本只出现在 XAML 定义的控件中。 如何让它在后面的代码中也能工作?

【问题讨论】:

  • 您是否遇到任何绑定错误?如果您删除控件的 XAML 副本,它是否有效?
  • 如果我删除它不起作用,但我刚刚注意到: System.Windows.Data Error: 40 : BindingExpression path error: 'Text' property not found on 'object' ''绑定'(HashCode=23914501)'。绑定表达式:路径=文本; DataItem='绑定' (HashCode=23914501);目标元素是 'Button' (Name='');目标属性是“内容”(类型“对象”)

标签: c# wpf xaml


【解决方案1】:

您将ContentControl.Content 设置为Binding,这与将Content 属性绑定到一个值不同。

要在后面的代码中绑定一个属性,你需要这样的语法:

var newControl new ContentControl();
newControl.ContentTemplate = Resource;

Binding b = new Binding();
b.ElementName = "TextBox";
b.Path = new PropertyPath(".");

myContentControl.SetBinding(ContentControl.ContentProperty, b);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 2012-03-30
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2018-09-24
    相关资源
    最近更新 更多