猿问

c#绑定前更改属性值

我不确定之前是否有人问过这个问题,但我目前处于将控件的属性绑定到 a 的情况。DependencyProperty但是,返回的值Property是类型Double。设置绑定时,如何20从属性中减去或给定值,然后绑定控件?我需要为此实施IValueConverter吗?我仍在学习 WPF,因此将不胜感激。


依赖属性


public static readonly DependencyProperty ProgressbarValueDependency = DependencyProperty.Register("PrValue", typeof(double),     typeof(LinearProgressBar));


public double PrValue

{

    get

    {

        return System.Convert.ToDouble(GetValue(ProgressbarValueDependency));

    }

    set

    {

        SetValue(ProgressbarValueDependency, value);

    }

}

绑定到属性


 {

MainGrid = GetTemplateChild("MainGrid");

Binding MainGridWidthBinding = new Binding("PrValue")

{

    Source = this,

    Mode = BindingMode.TwoWay

};

MainGrid.SetBinding(Grid.WidthProperty, MainGridWidthBinding);

}


子衿沉夜
浏览 169回答 2
2回答

SMILET

为了达到你的目的,你需要编写一个类实现IValueConverter接口。public class MyConverter : IValueConverter{    public object Convert(object value, Type targetType,         object parameter, string language)    {        // Contain your source to target convertion logic.     }    public object ConvertBack(object value, Type targetType,         object parameter, string language)    {        // Contain your target to source convertion logic.        // Only needed if using TwoWay or OneWayToSource Binding Mode.     }}然后Binding.Converter在调用SetBinding方法之前将其实例设置为属性 。Binding MainGridWidthBinding = new Binding("PrValue"){    Source = this,    Mode = BindingMode.TwoWay,    Converter = new MyConverter(),};MainGrid.SetBinding(Grid.WidthProperty, MainGridWidthBinding);
随时随地看视频慕课网APP
我要回答