【发布时间】:2014-11-19 01:56:25
【问题描述】:
我的 Windows Phone 8 Silverlight 应用程序的每个页面都有一个标题。为了停止重复我自己,我决定创建一个简单的 UserControl,它拥有一个 Grid 和一个 TextBlock。 TextBlock 的文本绑定到 UserControl (TitleProperty) 的 DependencyProperty。见文末代码。
为了使绑定到 TitleProperty 正常工作,我需要使用以下代码将 UserControl 的 DataContext 绑定到自身:DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"。
当在页面中使用控件并为 Title 属性设置 固定值 或 StaticBinding 时,这可以正常工作。例如:
这行得通:
<uiuc:SubSectionHeader Title="My fixed title" />
这适用于
<uiuc:SubSectionHeader Title="{Binding Source={StaticResource Literals}, Path=Literals.applicationSettings, FallbackValue='[Application Settings]'}" />
但是在进行正常绑定时它不起作用。例
<uiuc:SubSectionHeader Title="{Binding Path=UserName'}" />
那是因为 UserControl 在它自己的 DataContext 中寻找 UserName 属性(witch 是它自己),而不是在页面的 DataContext 中。 p>
问题 1:是否应该在将值传递给 Title 属性之前解析绑定?
问题2:是否只是覆盖了UserControl中中的绑定?
问题3:如何解决?请不要说改为创建自定义控件,因为这很糟糕
<UserControl x:Class="UI.UserControls.SubSectionHeader"
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"
xmlns:converters="clr-namespace:UI.Converters"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="50"
d:DesignWidth="480"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<UserControl.Resources>
<converters:StringCaseConverter x:Name="ToUppercase" />
<converters:BooleanToVisibilityConverter x:Key="BoolToVisibility" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot"
Height="50"
Background="{Binding Source={StaticResource ThemeSetter}, Path=BackgroundColor}">
<TextBlock VerticalAlignment="Center"
Margin="25 0 0 0"
Style="{StaticResource PhoneTextNormalStyle}"
Foreground="White"
Text="{Binding Path=Title, Mode=TwoWay, Converter={StaticResource ToUppercase}, ConverterParameter='upper', FallbackValue='[SUB SECTION TITLE]'}" />
</Grid>
</UserControl>
后面的代码:
using System.Windows;
using System.Windows.Controls;
namespace UI.UserControls {
public partial class SubSectionHeader : UserControl {
public SubSectionHeader() {
InitializeComponent();
}
public string Title {
get { return (string)GetValue( TitleProperty ); }
set { SetValue( TitleProperty, value ); }
}
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register(
"Title",
typeof( string ),
typeof( SubSectionHeader ),
new PropertyMetadata( "[SubSection Title]" )
);
}
}
【问题讨论】:
标签: xaml windows-phone-8 data-binding user-controls