C# WPF。将ImageBrush Viewbox属性绑定到对象时发生FormatException

C# WPF。将ImageBrush Viewbox属性绑定到对象时发生FormatException,c#,wpf,binding,viewbox,C#,Wpf,Binding,Viewbox,我正在尝试将ImageBrush的“Viewbox”属性绑定到代码隐藏处的类属性 我有两个图像,其想法是当我将鼠标移到顶部图像上时,底部图像在一个视图框中显示顶部图像的一部分,相对于鼠标位置。 代码只是为了在我学习WPF时进行测试,所以我知道它可能会更好,对不起 XAML代码: <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presen

我正在尝试将ImageBrush的“Viewbox”属性绑定到代码隐藏处的类属性

我有两个图像,其想法是当我将鼠标移到顶部图像上时,底部图像在一个视图框中显示顶部图像的一部分,相对于鼠标位置。 代码只是为了在我学习WPF时进行测试,所以我知道它可能会更好,对不起

XAML代码:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="MainWindow" Height="950" Width="525">
上述代码引发以下异常: System.Windows.Data错误:6:'TargetDefaultValueConverter'转换器无法转换值'ViewboxRect'(类型'String');如果可用,将使用回退值。BindingExpression:Path=;DataItem='String'(HashCode=1651705780);目标元素是“ImageBrush”(HashCode=47805141);目标属性为“Viewbox”(类型为“Rect”)FormatException:“System.FormatException:输入字符串的格式不正确

我尝试将“_rect”更改为字符串,但抛出了相同的错误。 当该属性是Rect而不是字符串时,为什么错误显示“converter无法转换值'ViewboxRect'(类型'String')”


谢谢。

依我看,你的装帧似乎不对。您正在绑定到主窗口的属性,因此它应该是:

<Rectangle Grid.Row="1">
    <Rectangle.Fill>
        <ImageBrush Stretch="UniformToFill"  ImageSource="descarga.png" ViewboxUnits="Absolute"
                    Viewbox="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MainWindow}}, Path=ViewboxRect}"/>
    </Rectangle.Fill>
</Rectangle>

此外,您应该考虑ReCt不执行<代码> NoTyFyPryTyType ,因此您的UI将不知道您在<代码>矩形LMyEMOVEO/<代码>方法中的更改。

private Rect _rect;

    public MainWindow()
    {
        InitializeComponent();
    }

    public Rect ViewboxRect
    {
        get
        {                
            return _rect;
        }
        set
        {
            _rect = value;
        }
    }
private void Rectangle_MouseMove(object sender, MouseEventArgs e)
    {
        Point p = e.GetPosition(this);
        _rect.X = p.X;
        _rect.Y = p.Y;
        _rect.Width = p.X + 10;
        _rect.Height = p.Y + 10;
    }
<Rectangle Grid.Row="1">
    <Rectangle.Fill>
        <ImageBrush Stretch="UniformToFill"  ImageSource="descarga.png" ViewboxUnits="Absolute"
                    Viewbox="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MainWindow}}, Path=ViewboxRect}"/>
    </Rectangle.Fill>
</Rectangle>