Set property in XAML for function

I need to set the cotrol property, which depends on another property of its parent. I am trying to better explain my problem with an example. I want to create a toggle button that animates a slider element. Toggle switch dimensions are determined when a user control is inserted into the application window. I want the slider to be larger than half the size of the switch case. Therefore, if the control is large 100, the slider should be 50, or if it is large 250, the slider should be 125. Then I need some kind of function call or something like that:

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

Is there any way to achieve this? thanks in advance Paolo

+4
source share
2 answers

Yes, you need data binding to the converter, for example, 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 will 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

+3
source

Out of the box, it is not XAML supported. You can bind to properties .

  • You can write a converter that performs the calculation (or you can use MathConverter )
  • You can perform the calculation in the code behind in the event handlers
  • If you follow the MVVM pattern, you can do the calculation in the ViewModel (although this will lead to a conceptual view of ViewModels, which is not always good ...)
  • You can write your own binding extension
+3
source

Source: https://habr.com/ru/post/1403884/


All Articles