WPF: Binding Margin/Thickness Left and Top Property

泄露秘密 提交于 2021-01-29 08:01:08

问题


I got a problem with bindings(i know why am i becoming this exception but dunno how to solve the problem).

I have tried this piece of code.

  <TextBlock HorizontalAlignment="Left" >
                        <TextBlock.Margin>
                            <Thickness Left="{Binding POSX.Value, Converter={StaticResource DPIConverter}}"
                                       Top="{Binding POSY.Value, Converter={StaticResource DPIConverter}}"/>
                        </TextBlock.Margin>
                    </TextBlock>

Im getting an exception where it says that, u cant bind thickness [LEFT], [TOP] properties. (ik why : cause those properties are not Dependency Property)

Thanks for ur help.

Edit : In case you didnt understand what am i trying to reach

-> I want to bind Left and Top Properties of Margin <-


回答1:


That's right you can't bind Left,Top,right or Bottom, because they are not dependency property. They are CLR property. DependencyProperty is wrapper to CLR Property.

Class which defines a dependency property must be inherited from the DependencyObject class. Thickness is a class which is not inherited from DependencyObject class. But the Margin is from TextBlock, which is inherited from FrameworkElement , and FrameworkElement inherited from UIElement, and UIElement is inherited from Visual which inherits from DependencyObject class.

What you can bind is Margin, since Margin is a dependency Property registered in FrameworkElement Class.

You can change your Xaml like this (sample code)

<TextBlock HorizontalAlignment="Left" Margin="{Binding POS, Converter={StaticResource DPIConverter}}" >

Below is the converter code, where we can send the whole thickness

 public class DPIConverter : IValueConverter
{
    public object Convert(object value, System.Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {    // your code inside Ivalue 
         // based pn some value send left and right value. other's can zero 
         // or which ever value you need. 
          int x = POS.PosX.Value;
          int y = POS.PoxY.Value;

        return new Thickness(System.Convert.ToDouble(x), System.Convert.ToDouble(y), 0, 0);
    }

    public object ConvertBack(object value, System.Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}


来源:https://stackoverflow.com/questions/53350240/wpf-binding-margin-thickness-left-and-top-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!