我有一個具有UserControl的MainWindow。當從ParentControl設置爲UserControl時,綁定不起作用
MainWindow綁定到ViewModel,它是DataContext。
現在使用MainWindowViewModel,我想綁定UserControl中的某些控件。
UserControl對每個我想要綁定的元素都有一個DependencyProperty。
從MainWindow我將UserControl的DependencyProperties綁定到MainWindowViewModel,但綁定不起作用。
主窗口XAML:
用戶控件XAML:
<ComboBox Grid.Column="0" Grid.Row="0" x:Name="ComboBoxVersions" SelectedIndex="0" Margin="10" ItemsSource="{Binding EnvironmentVersions}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Version " />
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
用戶控件代碼背後:
public partial class MultiSelectEnvironmentContextControl
{
public MultiSelectEnvironmentContextControl()
{
InitializeComponent();
this.DataContext = this;
}
public IEnumerable<string> EnvironmentVersions
{
get { return (IEnumerable<string>)GetValue(EnvironmentVersionsProperty); }
set { SetValue(EnvironmentVersionsProperty, value); }
}
// Using a DependencyProperty as the backing store for EnvironmentVersions. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EnvironmentVersionsProperty =
DependencyProperty.Register("EnvironmentVersions", typeof(IEnumerable<string>), typeof(MultiSelectEnvironmentContextControl), new PropertyMetadata(default(IEnumerable<string>)));
}
主窗口視圖模型:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Geico.Applications.Business.CoverageTestHarness.DomainLayer;
namespace Geico.Applications.Business.CoverageTestHarness.UIWPF.ViewModels
{
class TestRunnerControlViewModel: ViewModelBase
{
private DomainFacade domainFacade;
/// <summary>
/// Initializes a new instance of the <see cref="TestRunnerControlViewModel"/> class.
/// </summary>
public TestRunnerControlViewModel()
{
domainFacade = ((App) Application.Current).DomainFacade;
}
/// <summary>
/// Gets the environment versions.
/// </summary>
/// <value>
/// The environment versions.
/// </value>
public IEnumerable<string> EnvironmentVersions
{
get
{
return domainFacade.GetEnvironmentVersions();
}
}
}
}
在輸出什麼綁定錯誤? – netaholic
@netaholic我在輸出窗口中看不到任何錯誤。只是這些數據不是來自綁定後的數據。 – Charu
您的ViewModel類是私有的。讓它公開 – netaholic