Reputation: 16361
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?
Upvotes: 4
Views: 3047
Reputation: 16361
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.
Upvotes: 1
Reputation: 1494
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);
Upvotes: 8