Silverlight - 绑定控件的边框厚度

3

我是一个有用的助手,可以为您翻译文本。

我正在尝试更好地了解Silverlights绑定机制,因此创建了一个简单的程序,按下按钮即可更改列表框的边框厚度。但是它不起作用,我无法弄清楚我的错误在哪里。有什么想法吗?

XAML:

<Grid x:Name="LayoutRoot" Background="White">
    <ListBox Height="100" HorizontalAlignment="Left" Margin="134,102,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" BorderThickness="{Binding TheThickness, Mode=TwoWay}" />
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="276,36,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>

代码:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication4
{
    public partial class MainPage : UserControl
    {
        private TestClass testInst = new TestClass(); 

        public MainPage()

    {
        InitializeComponent();
        listBox1.DataContext = testInst;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        testInst.TheThickness = 10;
    }
}

public class TestClass
{
    private int theThickness = 5;

    public int TheThickness
    {
        get { return theThickness; }
        set
        {
            theThickness = value;

            NotifyPropertyChanged("TheThickness");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    // NotifyPropertyChanged will raise the PropertyChanged event, passing the source property that is being updated.
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

}

1个回答

4

边框厚度是Thickness类型的,它有多个值,包括上、下、左和右。XAML解析器知道如何正确处理类似BorderThickness="5"的内容,但在代码中你需要使用Thickness类型。例如:

public Thickness SelectedThickness
{
    get { return (Thickness)GetValue(SelectedThicknessProperty); }
    set { SetValue(SelectedThicknessProperty, value); }
}

public static readonly DependencyProperty SelectedThicknessProperty =
    DependencyProperty.Register("SelectedThickness", typeof(Thickness), typeof(MyRectangle),
    new PropertyMetadata(new Thickness() { Top = 1, Bottom = 1, Left = 1, Right = 1 }));
}

在这种情况下,默认的厚度为1。

编辑代码更像你的:

    private Thickness theThickness = new Thickness() {Left = 5, Right = 5, Top = 5, Bottom = 5};

    public Thickness TheThickness
    {
        get { return theThickness; }
        set
        {
            theThickness = value;

            NotifyPropertyChanged("TheThickness");
        }
    }

谢谢,我现在正在尝试让它工作。但是VS编辑器无法识别GetValue和SetValue的来源... - Calanus
抱歉,我只是从我已有的一些代码中剪切粘贴了一个真实的例子。SetValue和GetValue等内容假定对象是从DependencyObject派生的,你实际上不需要它们,只需将int的使用替换为Thickness并替换默认值分配即可。我会调整答案。 - AnthonyWJones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接