我试图在Silverlight 2.0中制作一个简单的填字游戏。我正在使用一个UserControl-ish组件,代表拼图中的一个正方形。我将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,Path = new PropertyPath( "ContentCharacter" ),Mode = BindingMode.TwoWay } );
这将在XAML中更加优雅。有没有人知道如何做?
解决方法
首先,使用{RelativeSource Self}在UserControl上设置DataContext:
<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" DataContext="{Binding RelativeSource={RelativeSource Self}}">
现在您可以将各个元素绑定到usercontrol的属性:
<TextBlock x:Name="Label" Grid.Row="0" Grid.Column="1" Text="{Binding LabelText}"/> <TextBox x:Name="Content" Grid.Row="1" Grid.Column="0" Text="{Binding ContentCharacter}" BorderThickness="0" />
对于SL 2.0,您需要在UserControl的Loaded事件处理程序中设置DataContext。
private void UserControl_Loaded( object sender,RoutedEventArgs e ) { LayoutRoot.DataContext = this; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。