Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating bindings in code (WinRT)

I have the following classes

ImageViewModel: INotifyPropertyChanged
{ ...
   String Url;
}

AdViewModel: INotifyPropertyChanged
{ ...
    ImageViewModel Image
}

The AdViewModel perodicaly changes the Image property (animated Ad).

When I have the following XAML:

<Grid>
  <Image Source="{Binding Image.Url}"
           Width="{Binding Image.Width}"
           Height="{Binding Image.Height}" />

And set the Grids DataContext to an instance of AdViewModel everything works as expected. But I need to create the XAML in C# code to use it elsewhere. Creating a Grid and appending an Image as its child is easy, but how to a create the bindings?

like image 203
Igor Kulman Avatar asked Jan 16 '23 09:01

Igor Kulman


2 Answers

try something along the lines of

AdViewModel vm = new AdViewModel;      
Binding binding = new Binding
{
    Path = new PropertyPath("Width"),
    Source = vm.Image
};
nameOfGridInXaml.SetBinding(Image.WidthProperty, binding);
like image 127
Maksim Satsikau Avatar answered Jan 17 '23 22:01

Maksim Satsikau


I found an easier way. I created the XAML as a UserControl, saved it in a file (Templates\SkyScrapper.xaml). Then instead of creating the controls in C# a just load the XAML File

 var _Path = @"Templates\SkyScrapper.xaml";
 var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
 var _File = await _Folder.GetFileAsync(_Path);
 var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File);

 DependencyObject rootObject = XamlReader.Load(_ReadThis) as DependencyObject;
 var uc = (UserControl)rootObject;

and set its DataContext

uc.DataContext = ad;

There is now no need to create the bindings in C#, they are defined in the XAML file.

like image 45
Igor Kulman Avatar answered Jan 17 '23 23:01

Igor Kulman