我正在尝试在Silverlight 2.0中制作一个简单的填字游戏。我正在开发一个类似UserControl的组件,用于表示拼图中的方格。我在将UserControl的属性与其元素绑定时遇到了麻烦。最终我(有点)解决了这个问题(对一些人可能有帮助——我花了几个小时),但是想要让它更加“优雅”。
我想象它应该有一个内容区和一个标签(位于右上角),可选地包含其编号。内容控件可能是TextBox,而标签控件可以是TextBlock。所以我创建了一个具有此基本结构的UserControl(值在此阶段为硬编码):
我想象它应该有一个内容区和一个标签(位于右上角),可选地包含其编号。内容控件可能是TextBox,而标签控件可以是TextBlock。所以我创建了一个具有此基本结构的UserControl(值在此阶段为硬编码):
<UserControl x:Class="XWord.Square"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
FontSize="30"
Width="100" Height="100">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock x:Name="Label" Grid.Row="0" Grid.Column="1"
Text="7"/>
<TextBox x:Name="Content" Grid.Row="1" Grid.Column="0"
Text="A"
BorderThickness="0" />
</Grid>
</UserControl>
我还在Square类中创建了这样的DependencyProperties:
public static readonly DependencyProperty LabelTextProperty;
public static readonly DependencyProperty ContentCharacterProperty;
// ...(static constructor with property registration, .NET properties
// omitted for brevity)...
我现在想弄清楚如何将Label和Content元素绑定到这两个属性。我是这样做的(在代码后台文件中):
Label.SetBinding( TextBlock.TextProperty, new Binding { Source = this, Path = new PropertyPath( "LabelText" ), Mode = BindingMode.OneWay } );
Content.SetBinding( TextBox.TextProperty, new Binding { Source = this, Path = new PropertyPath( "ContentCharacter" ), Mode = BindingMode.TwoWay } );
这个最好在XAML中完成,有没有人知道怎么做?