WPF的TabItem绑定属性

番茄爱上蛋 2018-09-11 09:32:34
背景:
这几天我在修改工具时碰到一个TabItem绑定属性和改变样式的问题。该工具以前TabControl的TabItem是写死的,现在我想将TabControl的ItemsSource绑定给后台的一个动态List。然而因为TabControl绑定的是一个自定义类CalWindow的List,TabItem 中的Header属性必须绑定这个类中的WindowName属性,所以我必须修改TabControl的itemTemplate。改完之后TabControl显示样式就各种不对劲,虽然这些样式问题可以重写样式来实现,但是我担心只是我之前的写法有问题才会这么麻烦。麻烦大佬们看看问题出在哪吧,非常感谢。

代码:

MainWindow:
<Window x:Class="TabItemStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TabItemStyle"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TabControl Height="37" HorizontalAlignment="Left" Margin="47,31,0,0" Name="tabControl1" VerticalAlignment="Top" Background="#FF38474E" ItemsSource="{Binding gWindowList}" SelectedItem="{Binding gCurrentWindow}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock FontFamily="Arial" Background="#FF38474E" FontWeight="Bold" Foreground="Black" FontSize="20" Padding="0" Text="{Binding WindowName}" />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</Grid>
</Window>


MainWindowViewModel:

using Microsoft.Practices.Prism.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TabItemStyle
{
public class MainWindowViewModel : NotificationObject
{
public MainWindowViewModel()
{
gWindowList = new ObservableCollection<CalWindow>
{
new CalWindow { WindowName = "September"},
new CalWindow { WindowName = "December"},
new CalWindow { WindowName = "June"},
new CalWindow { WindowName = "November"}
};
}

private ObservableCollection<CalWindow> _windowList = null;
public ObservableCollection<CalWindow> gWindowList
{
get
{
return _windowList;
}
set
{
_windowList = value;
this.RaisePropertyChanged(() => this.gWindowList);

if (_windowList != null)
{
gCurrentWindow = _windowList.First();
}
}
}

private CalWindow _currentWindow = null;
public CalWindow gCurrentWindow
{
get
{
return _currentWindow;
}
set
{
_currentWindow = value;
this.RaisePropertyChanged(() => this.gCurrentWindow);
}
}
}
}


CalWindow:

using System.Text;
using System.Threading.Tasks;

namespace TabItemStyle
{
public class CalWindow : NotificationObject
{
private string _windowName = "Unknown";
public string WindowName
{
get
{
return _windowName;
}
set
{
if (_windowName != value)
{
_windowName = value;
this.RaisePropertyChanged(() => this.WindowName);
}
}
}
}
}


...全文
507 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

110,525

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧