在XAML的绑定中是否可以只保留一部分边距

bvjveswy  于 10个月前  发布在  其他
关注(0)|答案(2)|浏览(80)

我有一个XAML,包含这样的信息:

... Margin="10,20,30,40" ...

字符串
我知道在装订中设置左边距非常容易,例如:

Margin="{Binding margin_value}"


.但这不会填充值“20,30,40”。
我在互联网上搜索的每一个地方,都看到了同样的答案:
你要找的是上、左、下和右。为了填充这些,这里是C#代码。
我对C#代码不感兴趣,我想直接在XAML中将其设置为绑定结果,但我尝试的所有方法(Margin.X="{Binding ...}"Margin.Left="{Binding ...}"Left.Margin="{Binding ...}",...)似乎都不起作用,尽管我相信它应该非常容易。
有人知道怎么做吗?
Thanks in advance

dbf7pr2w

dbf7pr2w1#

您可以根据需要指定四个厚度属性中的几个或多个,可以是LeftTopLeftButtom中的一个、两个、三个或四个。
然而,省略一个只会隐式地使它保持0的值。
所以你得到的只是不写0。
Margin或其他Thickness类型的属性的WPF内置转换器需要1,2或4个参数,但不是3个。
当你指定一个或两个时,它只是一个简写,所有四个值都将被应用。
因此,如果你不想指定其中一个,你可以用一个更详细的语法来命名属性:

<TextBox Text="Hello">
  <TextBox.Margin>
      <Thickness Left="8" Top="2" Bottom="2" /><!-- Right missing -->
  </TextBox.Margin>
</TextBox>

<TextBox Text="Hello">
  <TextBox.Margin>
      <Thickness Right="10" /><!-- Left Top Bottom -->
  </TextBox.Margin>
</TextBox>

字符串
但正如已经说过的,这只是一种指定此标记的冗长方法:

<TextBox Text="Hello" Margin="8 2 0 2" />
<TextBox Text="Hello" Margin="0 0 10 0" />


此外,thickness只是一个普通的结构体,它没有依赖属性,所以你不能绑定到指定的四维属性。结论:使用内置的类型转换器,指定所有4个值,其中简写不能满足你的要求。

r1zhe5dt

r1zhe5dt2#

您想要的语法可以通过如下所示的附加属性实现。

public static class Margin
{
    public static double GetLeft(DependencyObject obj) => (double)obj.GetValue(LeftProperty);
    public static void SetLeft(DependencyObject obj, double value) => obj.SetValue(LeftProperty, value);
    public static readonly DependencyProperty LeftProperty =
        DependencyProperty.RegisterAttached("Left", typeof(double), typeof(Margin),
            new PropertyMetadata(
                defaultValue: 0D,
                propertyChangedCallback: (d, e) =>
                {
                    if (d is FrameworkElement element)
                    {
                        element.Margin = new Thickness((double)e.NewValue, 0, 0, 0);

                        // If the other values should be kept.
                        // element.Margin = new Thickness((double)e.NewValue, element.Margin.Top, element.Margin.Right, element.Margin.Bottom);
                    }
                }));
}
<Button local:Margin.Left="100"/>

您可以添加顶部,右,底部,或其他东西。

相关问题