Friday, August 30, 2013

how to access an XAML control from code

I would use data binding to bind the Text property to a StaticResource that can be changed in the code behind.


1. Add a class with INotifyProperty change interface to act as the container for Units (This class could be useful for other places in your application as well.)



public class ViewModel : INotifyPropertyChanged
{
private string units;
public string Units
{
get { return units; }
set
{
units = value;
RaisePropertyChanged();
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}

2. Instantiate this class as a StaticResource in Page.Resources



<Page.Resources>
<local:ViewModel x:Key="myVM" />
</Page.Resources>

3. Add the data binding to your TextBlock in the DataTemplate



<TextBlock Text="{Binding Units, Source={StaticResource myVM}}" Margin="5,0,0,0" />

4. In the code behind, access the Units like this:



var vm = this.Resources["myVM"] as ViewModel;
vm.Units = "km";

When you change vm.Units, the display will also change.


No comments:

Post a Comment