繁体   English   中英

编写简单的转换器

[英]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 classClasses文件夹下Utils文件夹下的Converter文件夹内

您需要将Content属性绑定到源属性,才能调用Convert方法。 转换器仅与数据绑定一起使用。

这意味着,不用像下面这样在代码中设置LabelContent属性:

lblPercentage.Content = value;

您应该设置视图模型的source属性,然后将LabelContent属性绑定到:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM