有一个简单的XAML用户控件,我想将DataContext设置为(xaml.cs)文件后面的代码。WPF用户控件的datacontext代码隐藏属性
我想设置的DataContext和ItemsSource时在XAML,这样我就可以与物业ListOfCars填充组合框
XAML
<UserControl x:Class="Sample.Controls.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="85" d:DesignWidth="200">
<Grid Height="85" Width="200" Background="{StaticResource MainContentBackgroundBrush}">
<StackPanel Orientation="Vertical">
<ComboBox Height="23.338" x:Name="CarList" />
</StackPanel>
</Grid>
</UserControl>
代码背后
public List<Cars> ListOfCars
{
get { return _store.ListCars(); }
}
换句话说,而不是在代码隐藏中这样做,我如何设置绑定在XAML中
public MyControl()
{
InitializeComponent();
_store = new Store();
CarList.ItemsSource = _store.ListCars();
CarList.DisplayMemberPath = "Name";
}
不太理解{Binding viewModel}。这不起作用,但viewModel如何绑定到背后的代码,而不是在某种程度上挂钩它。没有针对此xaml的特定视图模型 – Kman
您必须在某处定义您的视图模型。这可以是你使用你的控件的'DataContext'(然后像这样绑定'{Binding}'),或者它可以是一个静态资源(然后像这样绑定'{Binding Source = {StaticResource * resource name *}} ,但你必须定义你要绑定到什么地方 – mydogisbox
通读以下关于绑定到视图模型的一些基础知识:http://msdn.microsoft.com/en-us/library/hh821028.aspx – mydogisbox