【发布时间】:2016-06-17 12:03:50
【问题描述】:
我是 C# UWP 开发的新手,我正在尝试在运行时更改 TextBlock 的值,但绑定无法正常工作。
我正在使用 INotifyPropertyChanged 将 XAML 中 TextBlock 的文本属性绑定到 ViewModel 上的属性,并且值每 10 秒更改一次。
我不知道这样做是否正确,有人可以帮助我吗?
提前致谢!
class MainPaigeViewModel : INotifyPropertyChanged
{
public MainPaigeViewModel()
{
Task.Run(async () =>
{
Random random = new Random();
while (true)
{
await Task.Delay(10000);
int newValue = random.Next(-40, 40);
_MyValue = newValue.ToString();
Debug.WriteLine(MyValue);
}
});
}
//Properties
private string _MyValue;
public string MyValue
{
get { return _MyValue; }
set
{
_MyValue = value;
RaisePropertyChanged("MyValue");
}
}
//INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CountDown2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModels="using:CountDown2.ViewModels"
x:Class="CountDown2.MainPage"
mc:Ignorable="d">
<Page.DataContext>
<ViewModels:MainPaigeViewModel/>
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<RelativePanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{Binding MyValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Width="100"
Height="40"
TextAlignment="Center"
FontSize="20"
/>
</RelativePanel>
</Grid>
</Page>
【问题讨论】:
-
你能在 Raisepropertychange 方法中放一个断点并检查它是否正在触发吗?
-
请在您的问题中就地提供您的代码,而不是作为外部链接。看看这里为什么给minimal reproducible example很重要。
-
@riteshmeher RaisePropertyChanged 没有触发,可能是什么问题?
标签: c# mvvm binding uwp uwp-xaml