WPF:绑定页边距/厚度左和顶部属性 [英] WPF: Binding Margin/Thickness Left and Top Property
问题描述
我遇到绑定问题(我知道为什么我会变成这个异常,但不知道如何解决此问题).
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>
我遇到一个例外,它说,您无法绑定厚度[LEFT],[TOP]属性.(例如,为什么:导致这些属性不是依赖属性)
Im getting an exception where it says that, u cant bind thickness [LEFT], [TOP] properties. (ik why : cause those properties are not Dependency Property)
感谢您的帮助.
以防万一您不了解我要达到的目标
Edit : In case you didnt understand what am i trying to reach
->我想绑定边距的左侧和顶部属性<-
-> I want to bind Left and Top Properties of Margin <-
推荐答案
是的,您不能绑定Left,Top,right或Bottom,因为它们不是依赖项属性.它们是CLR财产.DependencyProperty是CLR属性的包装.
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.
定义依赖项属性的类必须从DependencyObject类继承.厚度是一个不从DependencyObject类继承的类.但是Margin是从TextBlock继承的,TextBlock是从FrameworkElement继承的,而FrameworkElement是从UIElement继承的,UIElement是从Visual继承的,Visual是从DependencyObject类继承的.
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.
您可以绑定的是Margin,因为Margin是在FrameworkElement类中注册的依赖项属性.
What you can bind is Margin, since Margin is a dependency Property registered in FrameworkElement Class.
您可以这样更改Xaml(示例代码)
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;
}
}
这篇关于WPF:绑定页边距/厚度左和顶部属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!