gpt4 book ai didi

Silverlight - 绑定(bind)控制 borderthickness

转载 作者:行者123 更新时间:2023-12-04 02:42:41 25 4
gpt4 key购买 nike

我试图更好地理解 Silverlights 绑定(bind)机制,因此创建了一个简单的程序,可以在按下按钮时更改列表框的 borderthickness。但是它不起作用,我无法弄清楚我做错了什么。有什么想法吗?

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

最佳答案

边框厚度的类型为 Thickness,它有多个 Top、Bottom、Left 和 Right 值。 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");
}
}

关于Silverlight - 绑定(bind)控制 borderthickness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1900334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com