【问题标题】:WPF binding to fields worksWPF 绑定到字段有效
【发布时间】:2015-02-17 13:27:47
【问题描述】:

所以我一直认为 WPF 只绑定到属性

但是我将我的文本框绑定到一个公共字段并且它有效,你能向我解释一下吗?

这是我的文本框 XAML:

 <TextBox x:Name="afweh"  DataContext="Class1" HorizontalAlignment="Left" Height="24" Margin="225,13,0,0" TextWrapping="Wrap" Text="{Binding j}" VerticalAlignment="Top" Width="162"/>

这是我的领域:

public static class Class1
{
    public static string j="houmaaaaaaaaaaaani" ;
  //some code 
}

如你所见,“J”是一个字段,而不是一个属性

谢谢。

【问题讨论】:

  • 你的意思是它可以编译?我怀疑在运行时文本框显示“houmaaaaaaaaaaaani”。特别是因为DataContext="Class1" 将字符串“Class1”分配给TextBox 的DataContext,而不是Class1 的实例。所以这个类甚至没有在绑定中使用。

标签: c# wpf data-binding


【解决方案1】:

您不能绑定到静态或字段:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new Class1();
    }
}

public class Class1
{
    public static string j = "houmaaaaaaaaaaaani";
    public string J { get { return j; } set { j = value; } }
}

在 xaml 中:

<Window x:Class="WpfApplication4.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">
    <Grid>
        <TextBox x:Name="afweh" HorizontalAlignment="Left" Height="24" Margin="225,13,0,0" TextWrapping="Wrap" Text="{Binding J}" VerticalAlignment="Top" Width="162"/>
    </Grid>
</Window>

【讨论】:

  • 原来是 afweh.textbox=Class1.j;我忘了删除大声笑对不起
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多