简体   繁体   中英

Bind RenderTransform elements to code-behind variables

I'm following the answers given in this thread here: Access codebehind variable in XAML

Here's what I'm trying to do:

<Rectangle Name="MyRect" Fill="AliceBlue" MouseDown="Rectangle_MouseDown">
    <Rectangle.RenderTransform>
        <TransformGroup>
            <RotateTransform Angle="0" CenterX="300" CenterY="150"/>
            <TranslateTransform X="{DynamicResource TransX}" Y="0"/>
        </TransformGroup>
    </Rectangle.RenderTransform>
</Rectangle>

Then, I have a variable in my code behind which gets changed. It's called TransX and I add it as a resource:

public double TransX = 0;

public SvgPreview()
{
    InitializeComponent();
    SvgPreview1.Resources.Add("TransX", TransX);
}

The rectangle does get transformed properly from the start, however the transforms are not re-rendered to reflect changes in the TransX variable. What should I do?

Also, I have to do this exact same thing for several other values.

I think you should make SvgPreview implement INotifyPropertyChanged, set it as the DataContext of some parent of your Rectangle, and change TransX into a property and access it via DataBinding.

Edit: Like this:

<Rectangle Name="MyRect" Fill="AliceBlue" MouseDown="Rectangle_MouseDown"> 
    <Rectangle.RenderTransform> 
        <TransformGroup> 
            <RotateTransform Angle="0" CenterX="300" CenterY="150"/> 
            <TranslateTransform X="{Binding TransX}" Y="0"/> 
        </TransformGroup> 
    </Rectangle.RenderTransform> 
</Rectangle> 


class SvgPreview : INotifyPropertyChanged
// ......
private double transX;
public double TransX
{
    get { return transX; }
    set 
    {
        if(transX != value)
        {
            transX = value;
            OnNotifyPropertyChanged("TransX"); 
        } 
    }
}                

public SvgPreview() 
{ 
    InitializeComponent(); 
    TransX = 0;
}

and in the CodeBehehind of the Windows/Page/Control that contains your Rectangle;

// ...
InitializeCompenent();
this.DataContext = new SvgPreview();
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM