有一個簡單的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