http://www.microsoft.com/download/en/details.aspx?id=23887
Let's consider a simple example in which we need to define an application banner in a TextBlock. The application banner will provided by the view model so it needs to be bound to the TextBlock's Text property using Binding extension.
Let's consider a simple example in which we need to define an application banner in a TextBlock. The application banner will provided by the view model so it needs to be bound to the TextBlock's Text property using Binding extension. Let's update the MainPage as follows:
<UserControl x:Class="AppSilverlightBindingInStyle.MainPage" 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:local="clr-namespace:AppSilverlightBindingInStyle" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <UserControl.DataContext> <local:MainViewModel BannerText ="Application Banner" /> </UserControl.DataContext> <UserControl.Resources> <Style TargetType="TextBlock" > <Setter Property="Text" Value="{Binding BannerText}" /> <Setter Property="FontSize" Value="30" /> </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <TextBlock Name="bannerBox" TextAlignment="Center" /> </Grid> </UserControl>It has a simple TextBlock in the view. The DataContext is specified as MainViewModel. It has an inline assignment to its BannerText property. In the Resources we have a Style defined for the TextBlock. This would serve as the default Style of any TextBlock in the page unless overriden. Look at how we are able to bind the Value property of Style's Setter.
The view model just needs to have a property BannerText. The definition of MainViewModel used as DataContext in the above view is as follows:
namespace AppSilverlightBindingInStyle { using System.ComponentModel; public class MainViewModel : INotifyPropertyChanged { #region Properties string _bannerText; public string BannerText { get { return _bannerText; } set { _bannerText = value; OnPropertyChanged("BannerText"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void OnPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }When we run the application, it is shown as follows:
Download Code:
No comments:
Post a Comment