Dot-Net

此綁定的轉換器參數應該是什麼

  • April 20, 2012

我正在嘗試實現一個 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>

這些參數用於轉換器所需的常量。要為您的轉換器提供對象實例,您可以使用 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>

另一種方法是讓您的轉換器繼承自 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
}

在 XAML 中使用:

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

因此,您現在可以為轉換器中需要的每個參數聲明一個依賴屬性並綁定它。

引用自:https://stackoverflow.com/questions/377841