rebe21
rebe21

Reputation: 83

Set a property in XAML to a function

I need to set the property of cotrol which is a dependent of another property of its parent. I try to explain better my problem with an example. I want to create a toggle switch button that animates a "slider" element into it. The dimensions of the toggle switch is being defined when the usercontrol is inserted into the application window. I want the slider be sized half larger than the switch case. So if the control is large 100, the slider should be 50, or if large 250, the slider should be 125. Then I need a sort of call to a function or something similar:

<UserControl>
 <Border Name="switchCase" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Border Name="slider" Width="**Container.Width/2**" ></Border>
 </Border>
</UserControl>

Is there any possibilities to achieve this ?? Thanks in advance Paolo

Upvotes: 4

Views: 1490

Answers (2)

Klaus78
Klaus78

Reputation: 11906

Yes you need databinding with a converter, such as the following example

 xmlns:conv="clr-namespace:MyConverters.Converters"
 .......
    <UserControl.Resources>
        <conv:WidthConvertercs x:Key="widthConv"></conv:WidthConvertercs>
    </UserControl.Resources>
    <Border Name="switchCase" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
        <Border Name="slider" Width="{Binding ElementName=switchCase, Path=ActualWidth, Converter={StaticResource widthConv}}" Background="DarkMagenta"></Border>
    </Border>

Your converter class would be

[ValueConversion(typeof(double), typeof(double))]
    class WidthConvertercs : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double withPar = (double)value;
            return withPar/2.0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

I hope this helps

Upvotes: 3

nemesv
nemesv

Reputation: 139798

Out of the box it's not supported by XAML. You can only bind to Properties.

  • You can write a converter which do the calculation (or you can use MathConverter)
  • You can do the calculation in the code behind in event handlers
  • If you are following the MVVM pattern you can do the calculation in the ViewModel (altough it will introduce view related concepts to the ViewModels which is not always good...)
  • You can write your own Binding extension

Upvotes: 3

Related Questions