我想绑定文本框但它不显示字符串。第二件事是我想定期更新名称字符串。有什么解决办法吗?
这是我的 C# 代码:
public partial class Window1 : Window
{
public String Name = "text";
}
xml代码:
<Grid Name="myGrid" Height="300">
<TextBox Text="{Binding Path=Name}"/>
</Grid>
我想绑定文本框但它不显示字符串。第二件事是我想定期更新名称字符串。有什么解决办法吗?
这是我的 C# 代码:
public partial class Window1 : Window
{
public String Name = "text";
}
xml代码:
<Grid Name="myGrid" Height="300">
<TextBox Text="{Binding Path=Name}"/>
</Grid>
public partial class MainWindow : Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyCahnge("Name");
}
}
private void NotifyChange(string prop)
{
if(PropertyChanged!=null)
PropertyChanged(this,new PropertyChangedEventArgs(prop));
}
public event PropertyChangedEventHandler PropertyChanged;
}
希望这会有所帮助
您需要删除属性而不是字段,您在这里删除的是一个字段。
public String Name {get; set;}
另外,它不应该在控制文件(UI 文件)中。将其移动到单独的类并将其设置为 DataContext。
PLus 正如 Vlad 指出的那样,您需要通知 UI 事情发生了变化,简单的属性没有。
关于dataBinding的好文章:
您需要将您的定义Name
为DependencyProperty
:
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Window1));
(请注意,Visual Studio 为此定义了一个方便的代码段propdp
,请尝试键入propdp
++ 。TAB)TAB
然后,您需要正确绑定。像这样的东西:
<TextBox Text="{Binding Name, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>
WPF 绑定使用属性,而不是字段。您需要定义Name
为属性,并设置 Window 的数据上下文:
public partial class Window1 : Window
{
public String Name { get; set; }
public Window1()
{
Name = "text";
DataContext = this;
InitializeComponent();
}
}
如果您想支持更改通知和其他与 DP 相关的功能或使用INotifyPropertyChanged
. 我建议您在此处阅读有关 WPF 数据绑定的更多信息。