数据绑定从XAML到后面的代码

Ras*_*sto 11 .net c# data-binding wpf binding

Text在代码后面有这个依赖属性:

public static DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(MainWindow),
        new PropertyMetadata("Hello world"));

public string Text {
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

我想将label的内容绑定到该Text属性,以便标签显示Text属性的实际值,反之亦然.

<Label Content="{Binding ???}" />
Run Code Online (Sandbox Code Playgroud)

我该怎么做 ?

我之前做过一段时间,但现在我记不起来了 - 而且很简单.最简单的代码将被接受.

Had*_*ari 16

将Window/Control的DataContext设置为同一个类,然后在绑定上指定路径,如下所示:

public class MyWindow : Window {

    public MyWindow() {
        InitializeComponents();
        DataContext = this;
    }

    public string Text { ... }    
}

然后在你的xaml中:

<Label Content="{Binding Path=Text}">


Ari*_*oth 13

您必须设置窗口的DataContext才能工作.XAML:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" 
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
      <StackPanel>
        <Label Content="{Binding Text}" />
        <Button Content="Click me" Click="HandleClick" />
      </StackPanel>

    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MainWindow), new PropertyMetadata("Hello world"));
    public string Text 
    { 
        get { return (string)GetValue(TextProperty); } 
        set { this.SetValue(TextProperty, value); } 
    }

    public MainWindow()
    {
        InitializeComponent();
    }

    protected void HandleClick(object sender, RoutedEventArgs e)
    {
        this.Text = "Hello, World";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我的坏,忘记了DataContext.现在试试.抱歉.(经测试,它的工作原理.) (3认同)