这是我的用户控件的 XAML:
<UserControl x:Name="titledTextBox" x:Class="VitalStats.View.Controls.TitledTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480"
>
<Grid x:Name="LayoutRoot">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="titleTextBlock"
TextWrapping="Wrap"
Margin="12,5,0,-5"
Text="{Binding Title, ElementName=titledTextBox, FallbackValue=Title Here}"
FontSize="20"
Foreground="{StaticResource PhoneSubtleBrush}"/>
<TextBox x:Name="inputTextBox" Text="{Binding Text, ElementName=titledTextBox, Mode=TwoWay}"/>
</StackPanel>
</Grid>
</UserControl>
这就是我的代码隐藏的样子,
// Usings here
namespace VitalStats.View.Controls
{
public partial class TitledTextBox : UserControl
{
[Description("A TextBox with built in title")]
public TitledTextBox()
{
InitializeComponent();
if (DesignerProperties.GetIsInDesignMode(this) )
{
this.Title = "Title Here";
}
}
public string Title
{
get { return this.GetValue(TitleProperty) as string; }
set { this.SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(TitledTextBox), null);
public string Text
{
get { return this.GetValue(TextProperty) as string; }
set { this.SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(TitledTextBox), null);
}
}
将数据读入 UI 时绑定工作(因此该Title
属性可以正常工作)但是当从 UI 读取(即尝试Text
从代码访问)时,该属性始终为空,这意味着绑定只是单向的(尽管有该Mode=TwoWay
属性) .
我知道(感谢 XamlZealot 的回答)FindAncestor
绑定,但AncestorType
在 Windows Phone 7(或 Silverlight)XAML 命名空间中不存在。
UserControl
那么如何设置从内部到属性的双向绑定UserControl
?
这是在 Windows Phone 7(7.1 项目)上。