2009-12-14 94 views
3

我試圖更好地理解Silverlight綁定機制,因此創建了一個簡單的程序,它將改變按鈕按下時列表框的borderthickness。然而,它不起作用,我無法弄清楚我做錯了什麼。有任何想法嗎?Silverlight - 綁定到控件borderthickick

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

}

回答

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"); 
     } 
    } 
+0

謝謝,我試圖得到它的工作現在。 VS編輯器無法識別GetValue和SetValue來自哪裏... – Calanus 2009-12-14 11:44:49

+0

對不起,我只是從我已有的代碼中刪除了一個真實示例。 SetValue和GetValue的東西假設對象是從一個DependencyObject派生的,你實際上並不需要它們,只是用'Thickness'替換你對'int'的使用並替換你的默認值賦值。我會調整答案。 – AnthonyWJones 2009-12-14 12:06:06

+0

謝謝!你是個明星! – Calanus 2009-12-14 12:21:05