I have the following XAML code that I want to perform in xaml.cs.

<RichTextBox.LayoutTransform>
    <ScaleTransform ScaleX="{Binding ElementName=mySlider, Path=Value}"
                    ScaleY="{Binding ElementName=mySlider, Path=Value}"/>
</RichTextBox.LayoutTransform>

Basically it binds the slider to the richtextbox and performs zooming.

The following is what i have attempted:

RichTextBox newtext = new RichTextBox();
ScaleTransform mytran = new ScaleTransform();
mytran.ScaleX = mySlider.Value;
mytran.ScaleY = mySlider.Value;
newtext.LayoutTransform = mytran;
有帮助吗?

解决方案

The following code behind is equivalent to the Xaml

//<RichTextBox.LayoutTransform>
//    <ScaleTransform ScaleX="{Binding ElementName=mySlider, Path=Value}"
//                    ScaleY="{Binding ElementName=mySlider, Path=Value}"/>
//</RichTextBox.LayoutTransform>

ScaleTransform scaleTransform = new ScaleTransform();
Binding scaleXBinding = new Binding("Value");
scaleXBinding.Source = mySlider;
Binding scaleYBinding = new Binding("Value");
scaleYBinding.Source = mySlider;
BindingOperations.SetBinding(scaleTransform,
                             ScaleTransform.ScaleXProperty,
                             scaleXBinding);
BindingOperations.SetBinding(scaleTransform,
                             ScaleTransform.ScaleYProperty,
                             scaleYBinding);

RichTextBox newText = new RichTextBox();
newText.LayoutTransform = scaleTransform;

其他提示

you did set the transform but not the binding - it will be fixed. You need to use something like

Binding scaleBinding = new Binding("Value"){ElementName="mySlider"};
BindingOperations.SetBinding(mytran, ScaleTransform.ScaleXProperty, scaleBinding);
BindingOperations.SetBinding(mytran, ScaleTransform.ScaleYProperty, scaleBinding);

to really to the same

Not sure if you're asking how to perform the binding in code, or how to set the ScaleX and ScaleY properties in the code (e.g., without binding). If this is the case, here's how you'd do it:

First, give your ScaleTransform a name, e.g. "myScaleTransform":

<RichTextBox.LayoutTransform>
   <ScaleTransform x:Name="myScaleTransform" ScaleX="1" ScaleY="1" />
</RichTextBox.LayoutTransform>

Then, add an event handler for the ValueChanged event of mySlider. In this handler, update the ScaleX and ScaleY properties of myScaleTransform:

public void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    myScaleTransform.ScaleX = mySlider.Value;
    myScaleTransform.ScaleY = mySlider.Value;
}

Hope this helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top