Creating Bindings in Code (WinRT)

I have the following classes

ImageViewModel: INotifyPropertyChanged { ... String Url; } AdViewModel: INotifyPropertyChanged { ... ImageViewModel Image } 

The Perodicaly AdViewModel modifies 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 Grid DataContext to the instance of AdViewModel, everything works as expected. But I need to create XAML in C # code to use it elsewhere. Creating a grid and adding an image as its child is easy, but how do I create anchors?

+4
source share
2 answers

I found an easier way. I created XAML as a UserControl, saved it in a file (Templates \ SkyScrapper.xaml). Then instead of creating controls in C # 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 it to DataContext

 uc.DataContext = ad; 

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

+1
source

try something line by line

 AdViewModel vm = new AdViewModel; Binding binding = new Binding { Path = new PropertyPath("Width"), Source = vm.Image }; nameOfGridInXaml.SetBinding(Image.WidthProperty, binding); 
+8
source

Source: https://habr.com/ru/post/1438655/


All Articles