Silverlight - binding to a control border

I'm trying to better understand the Silverlights binding mechanism, and so I created a simple program that changes the value of the borderthickness listbox with a click of a button. However, this does not work, and I cannot understand what I am doing wrong. Any ideas?

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>

the code:

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));
        }
    }
}

}

+3
source share
1 answer

The thickness of the border is of a type Thicknessthat has several values ​​for the top, bottom, left and right. The XAML parser knows how to properly handle something like BorderThickness = "5", but you need to use a type in the code Thickness. For instance: -

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 }));
}

In this case, the default thickness is 1.

Change Code is more like yours: -

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

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

            NotifyPropertyChanged("TheThickness");
        }
    }
+4

Source: https://habr.com/ru/post/1725605/


All Articles