.net - 此绑定(bind)的转换器参数应该是什么

标签 .net wpf xaml converters

我正在尝试实现一个 wpf 用户控件,该控件使用转换器将文本框绑定(bind)到 double 列表。如何将用户控件的实例设置为转换器参数?

该控件的代码如下所示

谢谢

<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>

最佳答案

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

示例:用于乘以指定因子的值的转换器,该因子是从自定义控件 (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
}

在 XAML 中使用:

<MyConverter x:Key="MyConv"
             Factor={Binding ElementName=MyControl, Path=FactorValue}
/>

因此,您现在可以为转换器中需要的每个参数声明一个依赖属性并绑定(bind)它。

关于.net - 此绑定(bind)的转换器参数应该是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/377841/

相关文章:

javascript - 我可以创建跨浏览器兼容的 silverlight 页面而无需隐藏代码吗?

.net - 无法加载类型 'System.Web.Mvc.ViewUserControl<SOMETYPE>'

css - 没有 Ruby 的 SASS for .NET 应用程序

c# - 将 Web 浏览器控件锚定到所有四个方面

wpf - 在Blend 2013中未打开设计 View

wpf - TreeView MVVM,如何获得选择?

c# - 控制台应用程序中的 .NET Core 全局异常处理程序

.net - 这是什么控制?带下拉菜单的("Open"按钮)

c# - 如何将 Window 作为参数传递给 WPF C# 中的另一个类

c# - 如何在没有代码隐藏文件的情况下移动无边界 wpf 窗口