[英]Write simple converter
我有这个课程:
public class MyData
{
public static int Total Files;
public static int Total FilesFinished;
}
我有一个简单的Progress-Bar
,它以这种方式计算其Value
:
double value = ((double)MyData.FilesFinished / MyData.Files) * 100;
并使用简单的Timer
更新我的Label
:
Label name="lblPercentage" />
lblPercentage.Content = value;
现在,我想使用Converter
而不是通过后面的代码更新Label
。
所以我有这个课(尚未实现):
public class TotalFilesToTotalPercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在我的Window.Resource
内部,我有这个:
<Convertors:TotalFilesToTotalPercentageConverter x:Key="FilesToPercentageConverter "/>
这就是我在Label
尝试的方法:
Content="{Binding Converter={StaticResource FilesToPercentageConverter}}"
所以我的问题是,我尝试查看我的TotalFilesToTotalPercentageConverter
类是否通过调试器进行响应,但似乎没有,没有任何反应。
我做错了什么?
更新资料
我忘了提到我的TotalFilesToTotalPercentageConverter
class
在Classes
文件夹下Utils
文件夹下的Converter
文件夹内
您需要将Content
属性绑定到源属性,才能调用Convert
方法。 转换器仅与数据绑定一起使用。
这意味着,不用像下面这样在代码中设置Label
的Content
属性:
lblPercentage.Content = value;
您应该设置视图模型的source属性,然后将Label
的Content
属性绑定到:
Content="{Binding Path=YourValueProperty, Converter={StaticResource FilesToPercentageConverter}}"
将视图的DataContext
设置为视图模型类的实例:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
视图模型类需要实现INotifyPropertyChanged并在源属性( YourValueProperty
)的设置器中引发PropertyChanged
事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.