MultiValueConverter无法绑定到ViewModel

时间:2016-03-21 04:06:18

标签: c# wpf xaml mvvm user-controls

HelloAll:我正在尝试创建一个用户控件,需要一个MultiValueConverter来扩展我的应用中的画布:

需要

  1. Canvas.ActualWidth
  2. X Min of Engineering units
  3. X Max of Eng Units
  4. OPENSSL_NO_PADDING

    当我输入数字时,这似乎工作正常但是当我将XAML绑定到View模型时会出现问题:

    这是错误消息:

      

    错误7无法在“绑定”类型的“路径”属性上设置“绑定”。 '绑定'只能在DependencyObject的DependencyProperty上设置。 C:\ Users \ mwardell \ Documents \ Visual Studio 2013 \ Projects \ HalliburtonCallouts(12)\ HalliburtonCallouts \ HalliburtonCallouts \ View \ UserControls \ WellViewUserCtrl.xaml 31 38 HalliburtonCallouts

    public class MultiValueScaleTransform : IMultiValueConverter
    {
            public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
               double numerator     = (double)values[0];
               double denominator   = (double)values[2] - (double)values[1];
               return numerator / denominator;
            }
    
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    }
    

    我已确定 <UserControl x:Class="HalliburtonCallouts.View.UserControls.WellViewUserCtrl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Converters="clr-namespace:HalliburtonCallouts.ViewModel.Converters" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" x:Name="uc"> <UserControl.Resources> <Converters:ColorToImageBrush x:Key="ColorToBrush"/> <Converters:ColorToBitmapBrush x:Key="ColorToImg"/> <Converters:ColorToBG x:Key="ColorToBG"/> <Converters:ColorToFG x:Key="ColorToFG"/> <Converters:MultiValueScaleTransform x:Key="ScaleTransform"/> <SolidColorBrush x:Key="BlueBg" Color="#FFA9DCF1"/> </UserControl.Resources> <Border Background="Red"> <StackPanel> <!-- I used these to make sure the bindings of the user control are working--> <TextBlock Text="OverallStartDepth"></TextBlock> <TextBlock Text="{Binding OverallStartDepth}"></TextBlock> <TextBlock Text="OverallEndDepth"></TextBlock> <TextBlock Text="{Binding OverallEndDepth}"></TextBlock> <Canvas x:Name="WellCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource PreviousData}}" > <Canvas.RenderTransform> <ScaleTransform > <ScaleTransform.ScaleX > <MultiBinding Converter="{StaticResource ScaleTransform}"> <Binding Path="ActualWidth"/> <Binding Path="{Binding OverallStartDepth, FallbackValue=0.0}"/> <Binding Path="{Binding OverallEndDepth,FallbackValue=100.0}"/> </MultiBinding> </ScaleTransform.ScaleX> </ScaleTransform> </Canvas.RenderTransform> </Canvas> </StackPanel> </Border> </UserControl> OverallEndDepth是可绑定的。请参阅StackPanel前四项左右。不可绑定性证明它们是Dep Objects的Dep属性吗?

2 个答案:

答案 0 :(得分:2)

如错误所示,您不能使用{Binding},而是可以通过其名称获取元素并从其text属性中获取值。

<TextBlock Text="OverallStartDepth"></TextBlock>
<TextBlock Name="OverallStartDepthTextBlock" Text="{Binding OverallStartDepth}"></TextBlock>
<TextBlock Text="OverallEndDepth"></TextBlock>
<TextBlock Name="OverallEndDepthTextBlock" Text="{Binding OverallEndDepth}"></TextBlock>
<MultiBinding Converter="{StaticResource ScaleTransform}">
    <Binding Path="ActualWidth"/>
    <Binding ElementName="OverallStartDepthTextBlock" Path="Text"/>
    <Binding ElementName="OverallEndDepthTextBlock" Path="Text"/>
</MultiBinding>

注意: 您可以绑定OverallEndDepth是可绑定到任何控件的依赖项属性的值。

e.g。 TextBlock.Text是依赖属性 - SourceCode

    /// <summary>
    /// DependencyProperty for <see cref="Text" /> property.
    /// </summary>
    [CommonDependencyProperty]
    public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register(
                    "Text",
                    typeof(string),
                    typeof(TextBlock),
                    new FrameworkPropertyMetadata(
                            string.Empty,
                            FrameworkPropertyMetadataOptions.AffectsMeasure |
                            FrameworkPropertyMetadataOptions.AffectsRender,
                            new PropertyChangedCallback(OnTextChanged),
                            new CoerceValueCallback(CoerceText)));

    /// <summary>
    /// The Text property defines the content (text) to be displayed.
    /// </summary>
    [Localizability(LocalizationCategory.Text)]
    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

但是,Binding.Path是一个普通的属性,无法绑定,因此您得到上述错误 - SourceCode

/// <summary> The source path (for CLR bindings).</summary>
public PropertyPath Path
{
    get { return _ppath; }
    set
    {
        CheckSealed();

        _ppath = value;
        _attachedPropertiesInPath = -1;
        ClearFlag(BindingFlags.PathGeneratedInternally);

        if (_ppath != null && _ppath.StartsWithStaticProperty)
        {
            if (_sourceInUse == SourceProperties.None || _sourceInUse == SourceProperties.StaticSource ||
                FrameworkCompatibilityPreferences.TargetsDesktop_V4_0) // (for compat - Dev11 738992)
            {
                SourceReference = StaticSourceRef;
            }
            else
                throw new InvalidOperationException(SR.Get(SRID.BindingConflict,  SourceProperties.StaticSource, _sourceInUse));>             }
    }
}

答案 1 :(得分:2)

您无法在MultiBinding中绑定绑定的Path属性。相反,你只需在

中设置它们
<TextBlock Text="{Binding OverallStartDepth}">

相当于

<TextBlock Text="{Binding Path=OverallStartDepth}">

还有

<TextBlock>
    <TextBlock.Text>
        <Binding Path="OverallStartDepth"/>
    </TextBlock.Text>
</TextBlock>

因此MultiBinding应该像这样写:

<Canvas ... >
    <Canvas.RenderTransform>

        <MultiBinding Converter="{StaticResource ScaleTransform}">
            <Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType=Canvas}"/>
            <Binding Path="OverallStartDepth" FallbackValue="0.0"/>
            <Binding Path="OverallEndDepth" FallbackValue="100.0"/>
        </MultiBinding>
    </Canvas.RenderTransform>
</Canvas>

还要确保删除

DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource PreviousData}}"
来自画布的