C# XAML:初始化组件()后数据绑定到窗口不工作
我是XAML新手,我正在尝试将窗口(双陆棋棋盘)的score属性绑定到控件 通过代码隐藏,我能够使其按如下方式工作:C# XAML:初始化组件()后数据绑定到窗口不工作,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我是XAML新手,我正在尝试将窗口(双陆棋棋盘)的score属性绑定到控件 通过代码隐藏,我能够使其按如下方式工作: public partial class BgBoard : Window { public BgBoard() { InitializeComponent(); DataContext = this; _Score = 999; } private int _Score; public st
public partial class BgBoard : Window
{
public BgBoard()
{
InitializeComponent();
DataContext = this;
_Score = 999;
}
private int _Score;
public string Score { get { return _Score.ToString(); } }
}
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:bgb="clr-namespace:BackgammonBoard"
xmlns:Properties="clr-namespace:BackgammonBoard.Properties" x:Class="BackgammonBoard.BgBoard"
Title="Backgammon board" Width="750" Height="500" MinWidth="375" MinHeight="250">
<TextBlock x:Name="Player_Score" Text="{Binding Score}"/>
</Window>
现在,分数不再显示在我的用户界面上
但是,如果在调用initilizeComponent()之前在代码隐藏中初始化分数,分数将再次显示:
public BgBoard()
{
_Score = 999;
InitializeComponent();
}
因此,我的问题是,我应该在XAML中做些什么来确保每次在代码隐藏中修改分数时正确显示分数(而不仅仅是在初始化组件()之前初始化分数时)?您可以将数据绑定到
DependencyObject
的DependencyProperty
。窗口是一个DependencyObject
,因此您只需要一个DependencyProperty
…也不需要先将值转换为字符串。请尝试以下操作:
public static DependencyProperty ScoreProperty =
DependencyProperty.Register("Score", typeof(int), typeof(BgBoard));
public int Score
{
get { return (int)GetValue(ScoreProperty); }
set { SetValue(ScoreProperty, value); }
}
public BgBoard()
{
Score = 999;
InitializeComponent();
}
如果使用dependencProperty
,甚至可以从XAML文件将数据绑定到它,而无需设置窗口。DataContext
:
您看不到分数的原因是属性没有向UI发出“更改通知”,您需要实现“”(单击链接进行解释)Tx!但是,我尝试添加一个按钮来更改分数。但是,会显示分数的初始值,而不是按钮中更改的值。Tx!这很有效。当分数在代码隐藏中更改时,它现在会在UI中更新。欢迎使用StackOverflow。为了让您充分利用此网站,我建议您花些时间阅读StackOverflow的各个页面。特别是,现在您的第一个问题已经得到了回答,我想提请您注意帮助中心的页面。按照此处重要部分这些页面中的建议进行操作,因此如果您知道如何正确使用此网站,您将能够更好地利用它。
public static DependencyProperty ScoreProperty =
DependencyProperty.Register("Score", typeof(int), typeof(BgBoard));
public int Score
{
get { return (int)GetValue(ScoreProperty); }
set { SetValue(ScoreProperty, value); }
}
public BgBoard()
{
Score = 999;
InitializeComponent();
}
<TextBlock x:Name="Player_Score" Text="{Binding Score, RelativeSource={RelativeSource
AncestorType={x:Type YourLocalXamlNamespacePrefix:BgBoard}}}"/>