1
votes

I have a user control with a slider called MySlider within. I need to bind its value to the parent windows Datagrid:

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

I cannot access it by its Element Name, because it is inside of the UserControl (lets call it usercontrol).

I have already tried creating a public property in usercontrol:

public partial class usercontrol: UserControl 
{
    public double SliderValue { get { return (double)MySlider.Value; } }
}

and binding it to the DataGrid (given x:Name to the usercontrol):

<DataGrid.LayoutTransform>
   <ScaleTransform ScaleX="{Binding ElementName=usercontrolName, Path=SliderValue}"
                   ScaleY="{Binding ElementName=usercontrolName, Path=SliderValue}" />      
</DataGrid.LayoutTransform>

PROBLEM SOLVED thanks to GazTheDestroyer, see below (1) In MyUserControl.xaml at UserControl declaration:

<UserControl x:Class="..."
    Name="root">

(2) In MyUserControl.xaml at Slider:

<Slider Value="{Binding SliderValue, ElementName=root}"/>

(3) Other parts: see answer of GazTheDestroyer

1
Where is the UserControl and the DataGrid located in your window. Please post your XAML markup.mm8

1 Answers

1
votes

WPF bindings require change notification so your property won't work. The parent has no way of knowing when the slider's value has changed.

WPF has the concept of DependencyProperties which have notifications built in. You need to expose your slider value as a DependencyProperty on your UserControl

In MyUserControl.xaml.cs

public static readonly DependencyProperty SliderValueProperty = DependencyProperty.Register("SliderValue", typeof(double), typeof(MyUserControl), new PropertyMetadata((double)0));

public double SliderValue
{
    get
    {
        return (double)GetValue(SliderValueProperty );
    }
    set
    {
        SetValue(SliderValueProperty , value);
    }
}

This is what everything outside your UserControl will see and bind to, but you will need to hook it up to the Slider:

In MyUserControl.xaml

<Slider Value={Binding SliderValue, ElementName=root}" />

Now anything using MyUserControl can bind to SliderValue:

<DataGrid.LayoutTransform>
   <ScaleTransform ScaleX="{Binding ElementName=usercontrolName, Path=SliderValue}"
                   ScaleY="{Binding ElementName=usercontrolName, Path=SliderValue}" />      
</DataGrid.LayoutTransform>

This might seem like a lot of work, but the whole point of a Control is to encapsulate functionality and hide the implementation details from consumers. Depending on what you're trying to do you may not even need a separate UserControl, and could just bind to the Slider directly in the same view.