Binding part of margin

Shay Wilner 1,726 Reputation points
2020-08-03T17:53:31.27+00:00

Hi

How to bind part of margin i tried this but the xaml is wrong

 Margin="0, {x:Bind Path=xp ,Mode=OneWay} ,0,0"  

Thanks

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 32,231 Reputation points Microsoft Vendor
    2020-08-04T02:54:25.95+00:00

    Hello,

    Welcome to Microsoft Q&A!

    You could not use binding inside the margin value like what you did in your code. Margin is a Thickness Struct and the values inside of the struct are not dependency properties so you could not bind values to them directly.

    You will need to create a value converter to implement this. When you want to bind to some value, the converter could help to convert the value into a Thickness Struct which could be bind to the margin property.

    Here is the code that you could refer to:

    In the code behind:

     public sealed partial class MainPage : Page  
        {  
      
            public double testValue { get; set; }  
            public MainPage()  
            {  
                this.InitializeComponent();  
                testValue = 100.00;  
                this.DataContext = this;  
            }  
        }  
      
        public class MarginConverter : IValueConverter   
        {  
            public object Convert(object value, Type targetType, object parameter, string language)  
            {  
                return new Thickness(0, System.Convert.ToDouble(value), 0, 0);  
            }  
      
            public object ConvertBack(object value, Type targetType, object parameter, string language)  
            {  
                return null;  
            }  
        }  
    

    In xaml:

    <Page.Resources>
    <local:MarginConverter x:Key="MyConverter"></local:MarginConverter>
    </Page.Resources>

    <Grid>  
        <Rectangle Margin="{Binding testValue,Converter={StaticResource MyConverter}}" Fill="Red"/>  
    </Grid>  
    

    Thank you.

    0 comments No comments

0 additional answers

Sort by: Most helpful