- MVVM Binding to Custom Control in Windows Phone
- <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);}
- }
- }
- <Application.Resources>
- <PhoneApp1:MyControlViewModel x:Key="MCVM" />
- </Application.Resources>
- <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>
- <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 Text="{Binding MyLabel}" />
- <TextBlock Text="{Binding MyLabel,
- RelativeSource={RelativeSource FindAncestor,
- AncestorType=UserControl}" />
- <UserControl x:Class="PhoneApp1.MyControl"
- x:Name="root"
- x:SnipAttributesBecauseThisIsAnExample="true">
- <TextBlock Text="{Binding MyLabel, ElementName=root}" />
- </UserControl>