转换器参数应该用于此绑定

Dav*_*vey 11 .net wpf xaml converter

我正在尝试实现一个wpf用户控件,它使用转换器将文本框绑定到双精度列表.如何将用户控件的实例设置为转换器参数?

控件的代码如下所示

谢谢

<UserControl x:Class="BaySizeControl.BaySizeTextBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:local="clr-namespace:BaySizeControl"
    >
    <UserControl.Resources>
        <local:BayListtoStringConverter x:Key="BaySizeConverter"/>
    </UserControl.Resources>
    <Grid>

        <TextBox  Name="Textbox_baysizes" 
                  Text="{Binding RelativeSource={RelativeSource self},
                                Path=Parent.Parent.BaySizeItemsSource, 
                                Converter={StaticResource BaySizeConverter}}"
                  />
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

Joa*_*Fdz 11

另一种方法是使转换器继承自DependencyObject(或FrameworkElement).这允许您声明依赖项属性,从而可以从XAML设置其值,甚至是绑定.

示例:一个转换器,用于乘以指定因子的值,该值是从自定义控件(MyControl)中的属性(FactorValue)获取的.

转换器:

public class MyConverter : DependencyObject, IValueConverter
{
    // The property used as a parameter
    public double Factor
    {
        get { return (double) GetValue(FactorProperty); }
        set { SetValue(FactorProperty, value); }
    }

    // The dependency property to allow the property to be used from XAML.
    public static readonly DependencyProperty FactorProperty =
        DependencyProperty.Register(
        "Factor",
        typeof(double),
        typeof(MyConverter),
        new PropertyMetadata(1.15d));

    #region IValueConverter Members

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // Use the property in the Convert method instead of "parameter"
        return (double) value * Factor;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

在XAML中使用:

<MyConverter x:Key="MyConv"
             Factor={Binding ElementName=MyControl, Path=FactorValue}
/>
Run Code Online (Sandbox Code Playgroud)

因此,您现在可以为转换器中所需的每个参数声明一个依赖项属性并将其绑定.


Fre*_*ric 8

参数适用于转换器所需的常量.要为转换器提供对象实例,可以使用MultiBinding.

注意:要使此解决方案起作用,您还需要修改转换器以实现IMultiValueConverter而不是IValueConverter.幸运的是,所涉及的修改相当少.您可以为转换器提供的值数量添加验证,2在您的情况下.

<TextBox Name="Textbox_baysizes">
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource BaySizeConverter}">
            <Binding RelativeSource="{RelativeSource self}" Path="Parent.Parent.BaySizeItemsSource"/>
            <Binding ElementName="Textbox_baysizes"/>
        </MultiBinding>
    </TextBox.Text>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

  • 当然,您可以将对象引用作为转换器参数传递 - 确实必须将其视为常量,因为WPF无法在设置后重新绑定转换器参数,但这并不意味着它不能是对象参考! (2认同)