【发布时间】:2011-11-01 06:11:31
【问题描述】:
我有以下为 Windows Phone 应用程序定义的简单自定义控件。该控件的 XAML 如下:
<UserControl x:Class="PhoneApp1.MyControl"
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"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid x:Name="LayoutRoot">
<TextBlock Text="{Binding MyLabel}" />
</Grid>
此外,用户控件还有一个依赖属性,如下所示:
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly DependencyProperty MyLabelProperty =
DependencyProperty.Register("MyLabel", typeof (string), typeof (MyControl), new PropertyMetadata(default(string)));
public string MyLabel
{
get { return (string) GetValue(MyLabelProperty); }
set { SetValue(MyLabelProperty, value); }
}
}
现在的问题是,当我尝试将它数据绑定到我创建的视图模型时,什么也没有发生。各种代码项如下:
public class MyControlViewModel : ViewModelBase
{
private string name;
public string Name
{
get { return name; }
set { name = value;
RaisePropertyChanged(() => Name);}
}
}
在 App.xaml 中声明视图模型
<Application.Resources>
<PhoneApp1:MyControlViewModel x:Key="MCVM" />
</Application.Resources>
MainPage.xaml 控件的声明
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<PhoneApp1:MyControl x:Name="testControl" DataContext="{StaticResource MCVM}" MyLabel="{Binding Path=MyLabel}" />
</Grid>
但是,如果我尝试如下将其数据绑定到其他一些 UI 元素,它似乎可以工作?
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<PhoneApp1:MyControl x:Name="testControl" MyLabel="{Binding ElementName=Button, Path=Content}" />
<Button Click="Button_Click" x:Name="Button" Content="Click" />
</Grid>
我一直在努力让这个简单的场景发挥作用,我认为我遗漏了一些愚蠢的东西?
任何帮助将不胜感激
【问题讨论】:
-
你想在 TextBlock 中显示 MyLabel.Text 还是什么?
标签: mvvm windows-phone