XAML 管理MultiBinding中绑定的targetType

aor9mmx1  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(69)

所以,我有一个多绑定,其中一个转换器接受一些值并找到它们的最大值。问题是其中一个绑定使用了一个需要double目标类型的转换器,而绑定有一个object目标类型。我想知道是否有任何方法可以修改绑定的目标类型。
下面是我的xaml的近似值:

<TextBlock>
  <TextBlock.Width>
    <MultiBinding Converter="{StaticResource _maxValueConverter}">
      <Binding Source="{StaticResource _constantZeroValue}"/>
      <Binding Path="ActualWidth"
               ElementName="_previousTextBlock"
               Converter="{StaticResource _requiresDoubleTargetConverter}"/>
    </MultiBinding>
  </TextBlock.Width>
</TextBlock>

字符串
所以基本上,如果有任何方法可以告诉第二个绑定它正在输出一个双精度值,那就太好了。
最小可验证完整示例:
MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApplication1"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="350" Width="525">
   <StackPanel>
      <StackPanel.Resources>
         <sys:Double x:Key="constantZero">0</sys:Double>
         <local:RequiresDoubleTargetConverter x:Key="requiresDoubleTargetConverter" />
         <local:MaxValueConverter x:Key="maxValueConverter" />
      </StackPanel.Resources>

      <Border x:Name="topBorder"
              BorderThickness="1"
              BorderBrush="Black"
              HorizontalAlignment="Left">
         <TextBlock x:Name="topTextBlock"
                    Background="Aqua"
                    Text="{Binding TopText}" />
      </Border>

      <Border BorderThickness="1"
              BorderBrush="Black"
              MinWidth="100"
              HorizontalAlignment="Left">
         <TextBlock Background="ForestGreen"
                 Text="{Binding BottomText}"
                 TextWrapping="Wrap"
                 MinWidth="100">
            <TextBlock.Width>

               <MultiBinding Converter="{StaticResource maxValueConverter}">
                  <MultiBinding.Bindings>
                     <Binding Path="ActualWidth" ElementName="topTextBlock" Converter="{StaticResource requiresDoubleTargetConverter}" />
                     <Binding Source="{StaticResource constantZero}" />
                  </MultiBinding.Bindings>
               </MultiBinding>

            </TextBlock.Width>
         </TextBlock>
      </Border>

   </StackPanel>
</Window>


MainWindow.xaml.cs

using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace WpfApplication1
{
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      public string TopText
      {
         get { return "Hello World!"; }
      }

      public string BottomText
      {
         get { return "hi earth."; }
      }

      public MainWindow()
      {
         InitializeComponent();
      }
   }

   public class RequiresDoubleTargetConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         // I am looking for a way to manually ensure that "targetType == typeof(double)" evaluates to true.
         if (targetType != typeof(double))
         {
            return null;
         }
         else
         {
            // Actual converter performs this calculation.
            return (double)value - 14;
         }
      }

      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         // Irrelevant method for our purposes.
         throw new NotImplementedException();
      }
   }

   public class MaxValueConverter : IMultiValueConverter
   {
      public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
      {
         double max = double.NegativeInfinity;
         foreach (object value in values)
         {
            if (value is double)
            {
               max = Math.Max((double)value, max);
            }
            else
            {
               Debug.Fail("All values must be doubles");
            }
         }

         return max;
      }

      public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
      {
         // Irrelevant method for our purposes.
         throw new NotImplementedException();
      }
   }
}


这是使用Visual Studio 2015创建的,并经过验证以显示错误行为。我试图确定的是是否可以从xaml手动设置RequiresDoubleTargetConvertertargetType

f87krz0w

f87krz0w1#

就类型系统而言,绑定操作在object上。如果你想要一个特定的类型,你需要自己确保。
但是,您可以使用传递给转换器的目标类型来确定需要哪个类型,并相应地修改转换器的返回值。

vxqlmq5t

vxqlmq5t2#

那么,有没有办法手动设置转换器的目标类型,或者我坚持它是对象?
你只能使用object,因为Convert方法的签名总是相同的,也就是说,它只接受object[]的值。
Convert方法中,必须将values[1]转换为double(因为该方法将始终且仅传递object类型的值):

double d = (double)values[1];

字符串

4smxwvx5

4smxwvx53#

我已经想出了一个解决这个问题的方法,但是它只在你可以访问你在MultiBinding本身上使用的转换器的情况下才有效(或者你可以添加一个),如果它还使用ConverterParameter,TargetNullValue和/或StringFormat,那么就需要付出一些额外的努力。
诀窍在于,当你将子绑定添加到MultiBinding时,你将从该子绑定中删除Converter、ConverterParameter、TargetNullValue和StringFormat值,并将它们存储在MultiBinding的转换器的Convert方法可以访问的地方。(我们使用 Package 器MarkupExtension来模拟MultiBinding,这样我们就可以在它们实际应用之前访问所有内容,因为一旦它们被应用,你就不能更改它们了。)
然后在MultiBinding的Convert方法中,您现在从子绑定中获得原始的,尚未转换/格式化/合并的值,但您也有您需要的最终目标(在本例中为double),因为它被传递给您所在的MultiBinding的Convert方法。
有了这些信息,然后手动调用子转换器的Convert方法,传入尚未转换的值、targetType(传递给您)和childConverterParameter。
您获取该调用的结果,如果为null,则从子绑定返回TargetNullValue。
如果它不为null,并且两个targetType都是字符串,而你有一个String Format,最后格式化结果。
这里是伪代码(也就是说,在我的脑海中。可能有很多语法错误,等等。对于实际代码,你可以看到我在我的DynamicResourceBinding类中使用它,我在Stack Overflow here上使用它。

// Convert function for the MultiBinding
private object Convert(object[] values, Type targetType, object parameter, Culture culture){

    var rawChildBindingResult = values[0]; // assuming it's in the first position

    var convertedChildBindingResult = childConverter(rawChildBindingResult, targetType, childConverterParameter, culture);

    if(convertedChildBindingResult == null)
        convertedChildBindingResult = childTargetNullValue;
    else if(targetType == typeof(string) && childStringFormat != null)
        convertedChildBindingResult = string.Format(childStringFormat, convertedChildBindingResult);

    // Now do whatever you would with the 'convertedChildBindingResult' as if things were normal
}

字符串
再次,看看链接,看看它的上下文。

相关问题