[英]Why this WPF TabControl Binding Interface Error?
这是我下面的代码,但为什么一个(Test1View)不起作用而另一个(Test2View)起作用?
我想了很久,但没有想法。 谁能有想法? 我应该阅读哪些文件?
1、主窗口.xaml:
<StackPanel>
<TabControl Height="300" ItemsSource="{Binding TabCollection}">
<!-- this is the header template-->
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding DisplayIndex}" />
<Image Source="{Binding ContentObject.BackgroundImageSource}" Width="50"></Image>
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
<!-- this is the body of the TabItem template-->
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding ContentObject.ShowContent}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</StackPanel>
2、主窗口.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
vm = new WindowVM();
this.DataContext = vm;
InitializeComponent();
vm.Init();
}
private WindowVM vm;
}
3、视图模型:
public class WindowVM
{
public ObservableCollection<ITestView> TabCollection { get; } = new ObservableCollection<ITestView>();
public void Init()
{
List<ITestView> list = new List<ITestView>()
{
new Test1View(), // it doesn't work
new Test2View(), // it work
};
TabCollection.Clear();
foreach (ITestView test in list)
{
TabCollection.Add(test);
}
}
}
4、接口:ITestView、IContentTest
public interface ITestView
{
IContentTest ContentObject { get; set; }
int DisplayIndex { get; set; }
}
public interface IContentTest
{
string ShowContent { get; set; }
ImageSource BackgroundImageSource { get; set; }
}
5、DataSource:Test1View,不行。
public partial class Test1View : UserControl,ITestView //Test1View is a UserControl,Test1View.xaml is only a block grid.
{
public Test1View()
{
InitializeComponent();
}
public IContentTest ContentObject { get; set; } = new ContentTest1();
public int DisplayIndex { get; set; } = 1;
}
public class ContentTest1 : IContentTest
{
public ContentTest1()
{
ShowContent = "header111";
BackgroundImageSource = Application.Current.FindResource("Image111") as ImageSource; // <ImageSource x:Key="Image111">aaa.png</ImageSource>
}
public string ShowContent { get; set; }
public ImageSource BackgroundImageSource { get; set; }
}
6、DataSource:Test2View,可以,为什么Test1View不行? 但是 Test2View 工作吗?
public class Test2View : ITestView
{
public IContentTest ContentObject { get; set; } = new ContentTest2();
public int DisplayIndex { get; set; } = 2;
}
public class ContentTest2 : IContentTest
{
public ContentTest2()
{
ShowContent = "header222";
BackgroundImageSource = Application.Current.FindResource("Image111") as ImageSource; //<ImageSource x:Key="Image111">aaa.jpg</ImageSource>
}
public string ShowContent { get; set; }
public ImageSource BackgroundImageSource { get; set; }
}
对于 Test1View,您可能必须直接在视图中执行绑定。 但是TabControl
也无法显示它,因为模板不考虑直接绑定另一个视图。
这可以通过 ItemTaplate 中的ContentControl
来完成。 通常,您不能轻易地在模板中显示两种不同类型的内容,在您的示例中,这是一个视图(Test1View)和一个 viewModel(Test2View)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.