设置绑定边距

use*_*195 11 c# wpf xaml binding margin

我有一个绑定值,返回一个int,表示我没有分配给元素的左右边距的值.

继承人我尝试过但它不会编译.

如果我设置整个边距,它可以工作,但我只想要左右.

XAML:

<Image x:Name="_image" Source="mat.png" Margin="{Binding EditorRow.BondIndent},0,{Binding EditorRow.BondIndent},0" />
Run Code Online (Sandbox Code Playgroud)

类:

public int BondIndent
{
    get { return _bondSequence * 5; }
}
Run Code Online (Sandbox Code Playgroud)

Luu*_*uuk 22

退还保证金?

public Thickness Margin
{
    get { return new Thickness(BondIndent,0,BondIndent,0);}
}
Run Code Online (Sandbox Code Playgroud)

然后改变:

<Image x:Name="_image" Source="mat.png" Margin="{Binding EditorRow.Margin}" />
Run Code Online (Sandbox Code Playgroud)


ody*_*jii 13

您可能需要使用ValueConverter.就像是:

public class LeftRightThicknessConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is int)
        {
            int margin = (int)value;
            return Thickness(margin, 0, margin, 0);
        }
        return Thickness();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过以下方式使用转换器:

<Grid>
    <Grid.Resources>
        <xxx:LeftRightThicknessConverter x:Key="LeftRightThicknessConverter" />
    </Grid.Resources>

    <Image Margin="{Binding SomePropertyPath, Converter={StaticResource LeftRightThicknessConverter}}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

假设这xxx是一个有效的xml命名空间.