Reputation: 7671
If I have code in a code behind class that does this:
MyElement.Content = new XamlUserControlFile();
How can I do the same thing in xaml?
Upvotes: 1
Views: 1197
Reputation: 8182
Perhaps what you want is a ContentControl with a XAML that contains a usercontrol?
There are some restrictions on the content of a ContentControl though, as you can see here. The content has to be Text (sporting a ToString() method) or an UIElement derived object.
You can simply build some kind of UserControl an place that in an ContentControl, separating xaml from use of the control.
Update
Utilizing a MVVM framework like caliburn.micro will let you stick very close to MVVM. You just reference ViewModels from ViewModels. You can get entirely rid of code-behind.
Lets say you have a UserControl like
<UserControl x:Class="MyUserControlView"
...>
<Grid Background="Green">
</Grid>
</UserControl>
Then you have some ViewModel for it:
public class MyUserControlViewModel : PropertyChangedBase
{
}
Then you very easyly can have a Binding for that in the Screen (View and ViewModel) that shall contain that UserControl
public MyUserControlViewModel MyUserControlViewModel { get; set; }
initialize it via constructor injection in the containing class
public ShellViewModel(MyUserControlViewModel viewModel)
{
this.MyUserControlViewModel = viewModel
}
and set up the Binding (in the containing XAML) like:
<ContentControl Name="MyUserControlViewModel " />
This is all you have to do, it is as easy as that.
Please note that caliburn.micro has "convention over configuration", so you have to name your Views "...View" and your ViewModels "...ViewModel". (But you can set up your own rules).
And, very important in this example:
caliburn.micro can and will setup a binding from an <x:Name="...">
as you can
see in the ContentControl above.
Upvotes: 1
Reputation: 14302
It's not entirely clear, but short of some more info...
If you're using something like...
hostControl.Content = XamlReader.Load(YourXAML);
Or LoadComponent
etc.
I don't think there is anything 'shorthand' in XAML (if there is I'd like to see it:).
1) You could use one of...
Content="{x:Static my:YourStaticClass.XAMLProperty, Converter=...}"
Content="{Binding Source={x:Static my:YourStaticClass.XAMLProperty}, Converter=...}"
Content="{Binding ViewModelXAMLProperty}, Converter=...}"
To bind to a property which exposes the Content
or inner Control
(which is loaded and prepared) you'd like to put in there.
You'd need to prepare
it so it's in the form you want (straight XAML won't work but some form of load).
I've specified Converter
as that's another way - you can convert your XAML on the fly - if that's required.
2) You could also Load
the XAML from the code behind - and put it into resources - or define some wrapper which you instantiate in the XAML.
And then you use {StaticResource ...}
or DynamicResource etc.
Possibilities are endless - you should put up some more relevant info.
Upvotes: 1