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

栏目: 编程工具 · 发布时间: 5年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/8580477/how-to-bind-local-property-on-control-in-wpf

我有两个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}" />

我们可以看到标签绑定到本地属性(在代码后面),当我点击按钮时,我没有看到任何值的标签

以下是我的代码背后…

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

问候,

尝试

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

希望有所帮助

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/8580477/how-to-bind-local-property-on-control-in-wpf


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Machine Learning

Machine Learning

Kevin Murphy / The MIT Press / 2012-9-18 / USD 90.00

Today's Web-enabled deluge of electronic data calls for automated methods of data analysis. Machine learning provides these, developing methods that can automatically detect patterns in data and then ......一起来看看 《Machine Learning》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具