[英]Binding to an Static property of an Static class doesn't work
I'm trying to Bind
the Text
property of the TextBlock
to StaticClass.Percent
. 我试图将
TextBlock
的Text
属性Bind
到StaticClass.Percent
。 Since I couldn't do that (Or could I?) I have defined the LoadingPercent
in my ViewModel
so that I can bind to it. 由于无法执行此操作(或者可以执行?),因此我在
ViewModel
定义了LoadingPercent
,以便可以绑定到它。 It is still not working. 它仍然无法正常工作。 How can I solve this?
我该如何解决? Or can I bind to the StaticClass directly and ignore the ViewModel approach?
还是可以直接绑定到StaticClass而忽略ViewModel方法?
<Window x:Class="TestBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:testBinding="clr-namespace:TestBinding"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<testBinding:ViewModel/>
</Window.DataContext>
<StackPanel>
<TextBlock Width="100"
HorizontalAlignment="Center"
Text="{Binding LoadingPercent}"/>
<Button Content="Change"
Width="200"
Height="30"
Margin="0 20 0 0"
HorizontalAlignment="Center"
Click="ChangeText"/>
</StackPanel>
</Window>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void ChangeText(object sender, RoutedEventArgs e)
{
StaticClass.Percentage = 10;
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double loadingPercent;
public double LoadingPercent
{
get { return StaticClass.Percentage; }
set
{
loadingPercent = value;
RaisePropertyChanged("LoadingPercent");
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public static class StaticClass
{
public static int Percentage { get; set; }
}
Here is a mistake: 这是一个错误:
private double loadingPercent;
public double LoadingPercent
{
get { return StaticClass.Percentage; }
set
{
loadingPercent = value;
RaisePropertyChanged("LoadingPercent");
}
}
You return in get
the StaticClass.Percentage
but you assign loadingPercent
in set. 你返回
get
的StaticClass.Percentage
但分配loadingPercent
在集。
I am not sure why you need the static class after all, but if you want to ditch the viewmodel and bind directly to the static property, see here 我不确定为什么毕竟需要静态类,但是如果您想抛弃viewmodel并直接绑定到static属性, 请参见此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.