我正在尝试实现一个 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/