简体   繁体   English

为什么不能绑定保证金属性?

[英]Why can't I bind the margin property?

I have a board of rectangles which I want to scale dynamically. 我有一个要动态缩放的矩形板。 I can set the Height and Width properties of the rectangle element. 我可以设置矩形元素的Height和Width属性。 The only property that doesn't cooperate is the margin.. 不合作的唯一属性是保证金。

I tried binding the same property margin in my ViewModel to either width, height and margin and it only works well with the width and height. 我尝试将ViewModel中的相同属性边距绑定到宽度,高度和边距,并且只能与宽度和高度一起使用。 As soon as I try it on the margin property of the rectangle it takes a lot of time to load the window AND it eventually shows up with no margin at all.. 一旦我在矩形的margin属性上尝试它,就会花费很多时间来加载窗口,并且最终显示出来时根本没有空白。

Does anyone know why this is happening? 有人知道为什么会这样吗?

Rectangle: 长方形:

<Rectangle Margin="{Binding ElementName=root, Path=DataContext.Margin}" Fill="White" Height="{Binding ElementName=root, Path=DataContext.Margin}" Width="{Binding ElementName=root, Path=DataContext.Margin}"></Rectangle>

Property: 属性:

private int _margin = 5;
    public int Margin
    {
        get
        {
            return _margin;
        }
    }

I think your issue might have been with the way in which you're binding because I was not able to reproduce the issue. 我认为您的问题可能与绑定的方式有关,因为我无法重现该问题。 Perhaps you could post more code to determine the exact cause. 也许您可以发布更多代码以确定确切原因。 However, the following worked for me: 但是,以下对我有用:

XAML: XAML:

<Window.Resources>
    <local:MyRectangle x:Key="myRectangle" />
</Window.Resources>

<Grid DataContext="{StaticResource myRectangle}">
        <Rectangle Width="{Binding Path=MyWidth}" Height="{Binding Path=MyHeight}" Margin="{Binding Path=MyMargin}"  />
</Grid>

CLASS CODE: 班级代码:

public class MyRectangle
{
    public double MyMargin { get; set; }
    public double MyWidth {get; set;}
    public double MyHeight {get; set;}

    public MyRectangle(double dHeight, double dWidth, double dMargin)
    {
        MyHeight = dHeight;
        MyWidth = dWidth;
        MyMargin = dMargin;
    }
}

Alright, I fixed it! 好吧,我已修复它! It seemed to be a problem to use int or double as margin.. margin is of type Thickness! 使用int或double作为margin似乎是一个问题。margin是Thickness类型的! Thanks for all the help anyway! 无论如何,感谢您的所有帮助!

private Thickness _vakMargin;
public Thickness VakMargin
{
    get
    {
        return _vakMargin;
    }
    set
    {
        _vakMargin = value;
    }
}

I did set it for all 4 margins with: 我确实为所有4个边距设置了它:

new Thickness(someDouble);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM