如何在WPF中绑定控件上的本地属性

时间:2011-12-20 18:54:10

标签: wpf binding properties local

我在WPF上有两个控件

<Button HorizontalAlignment="Center"
        Name="btnChange"
        Click="btnChange_Click"
        Content="Click Me" />

<Label Name="lblCompanyId"
       HorizontalAlignment="Center"
       DataContext="{Binding ElementName=_this}"
       Content="{Binding Path=CompanyName}" />

正如我们可以看到标签绑定到本地属性(在代码Behind中),当我点击按钮时,我在标签上看不到任何值...

以下是我背后的代码......

public static readonly DependencyProperty CompanyNameProperty =
  DependencyProperty.Register("CompanyName", typeof(string), typeof(Window3), new UIPropertyMetadata(string.Empty));

public string CompanyName {
  get { return (string)this.GetValue(CompanyNameProperty); }
  set { this.SetValue(CompanyNameProperty, value); }
}

private void btnChange_Click(object sender, RoutedEventArgs e) {
  this.CompanyName = "This is new company from code beind";
}

此致

2 个答案:

答案 0 :(得分:38)

Content="{Binding ElementName=_this, Path=CompanyName}"

没有DataContext绑定

修改

我的代码没有问题,将您的窗口命名为x:Name="_this"

<Window x:Class="WpfStackOverflowSpielWiese.Window3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window3"
        Height="300"
        Width="300"
        x:Name="_this">
  <Grid>
    <StackPanel>
      <Button HorizontalAlignment="Center"
              Name="btnChange"
              Click="btnChange_Click"
              Content="Click Me" />

      <Label Name="lblCompanyId"
             HorizontalAlignment="Center"
             DataContext="{Binding ElementName=_this}"
             Content="{Binding Path=CompanyName}"></Label>

    </StackPanel>
  </Grid>
</Window>

并且您的窗口真的是Window3吗?

public partial class Window3 : Window
{
  public Window3() {
    this.InitializeComponent();
  }

  public static readonly DependencyProperty CompanyNameProperty =
    DependencyProperty.Register("CompanyName", typeof(string), typeof(Window3), new UIPropertyMetadata(string.Empty));

  public string CompanyName {
    get { return (string)this.GetValue(CompanyNameProperty); }
    set { this.SetValue(CompanyNameProperty, value); }
  }

  private void btnChange_Click(object sender, RoutedEventArgs e) {
    this.CompanyName = "This is new company from code beind";
  }
}

希望有所帮助

答案 1 :(得分:5)

您目前正在将您的Label的DataContext绑定到Button,然后尝试将其Content设置为CompanyName,但CompanyName无效Button

上的财产

在绑定DataContext中指定Path以绑定到Button.DataContext.CompanyName而不是Button.CompanyName

另外,我建议只绑定Content而不是绑定DataContext和Content

<Label Content="{Binding ElementName=btnChange, Path=DataContext.CompanyName}" />

如果您的代码看起来与发布的代码示例完全相同,那么ButtonLabel都具有相同的DataContext,因此您可以直接绑定到CompanyName < / p>

<Label Content="{Binding CompanyName}" />

修改

注意到你的Label的绑定是一个名为_this的控件。我原以为是Button,虽然我现在看到你的Button的名字是btnChange,而不是_this

尽管如此,答案仍然是一样的。您正在尝试绑定到UI Control的CompanyName属性,该属性不是有效属性。