如何绑定到Button BorderThickness?

时间:2012-10-04 11:53:50

标签: c# xaml data-binding windows-8 microsoft-metro

我在xaml中为Button类创建了一个自定义样式。以下是相关部分:

<Rectangle
    Stroke="{TemplateBinding BorderBrush}"
    StrokeThickness="{TemplateBinding BorderThickness}"/>

显然这不起作用,因为虽然StrokeThicknessdouble,但BorderThicknessThickness

如何在不弄乱转换器的情况下绑定厚度的实际值(总是均匀的)?

在您标记为完全重复之前,this question是不同的。

2 个答案:

答案 0 :(得分:4)

试试这个:

<Rectangle
    Stroke="{TemplateBinding BorderBrush}"
    StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, 
        Path=BorderThickness.Left}"/>

注意

以下绑定

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MyProperty}

相同
{TemplateBinding MyProperty}

答案 1 :(得分:0)

怎么样

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:Con x:Key="abc" />
    </Window.Resources>
    <Grid>
        <Rectangle StrokeThickness="{Binding abc, Converter={StaticResource abc}}"/>
    </Grid>
</Window>


namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new { abc = new Thickness(4) };
        }
    }    

    public class Con : IValueConverter
    {
        public object Convert(object value, Type targetType, 
                              object parameter, 
                              System.Globalization.CultureInfo culture)
        {
            return ((Thickness)value).Left;
        }

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