简体   繁体   English

WPF简单绑定在代码后面

[英]WPF simple bind in code behind

I try to learn WPF, I have problem with basic binding, at the beginning I want to set bind in code behind. 我尝试学习WPF,基本绑定有问题,一开始我想在后面的代码中设置绑定。 May anyone know what I make wrong? 谁能知道我做错了什么?

Fils CS Fils CS

public partial class BindInCodeBehind : Window, INotifyPropertyChanged
{
    private string _myText;

    public string MyText
    {
        get { return _myText; }
        set
        {
            _myText = value;
            OnPropertyChanged("MyText");
        }
    }

    public BindInCodeBehind()
    {
        InitializeComponent();

        var bind = new Binding();
        bind.Source = MyText;
        bind.Path = new PropertyPath("Content");

        MyLabel.SetBinding(Label.ContentProperty, bind);

        MyText = "New tekst";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

File XAML 文件XAML

<Window x:Class="WpfBindingLearn.BindInCodeBehind"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="BindInCodeBehind" Height="300" Width="300">
    <Grid>
        <Label Name="MyLabel" Content="Wait for binding"></Label>
    </Grid>
</Window>

Path is set in relation to current binding source. 相对于当前绑定源设置了Path Your source (which is a String ) does not have Content property. 您的源(是String )没有Content属性。 You can set Source to Window and Path to MyText 您可以将Source设置为Window ,将PathMyText

var bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("MyText");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM