【发布时间】:2018-10-05 19:49:43
【问题描述】:
我想用 TabControl 创建应用程序。
我想将 UserControls 放在选项卡上,但我不会在 *.cs 文件中创建它,而是使用绑定。
我有应用程序,可以在其中添加带有用户控件的选项卡,但我不知道如何将字符串与选项卡名称绑定。
我的代码:
MainWindow.xaml.cs
using System.Windows;
namespace WpfApp3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
MainWindow.xaml
<Window x:Class="WpfApp3.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:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TabControl ItemsSource="{Binding UserControls}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="???" /> <!--binding? -->
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
<Button Grid.Row="1" Content="Dodaj zakładkę" Command="{Binding AddButtonCommand}"/>
</Grid>
</Window>
MainWindowViewModel.cs
using Prism.Commands;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp3
{
class MainWindowViewModel : BindableBase
{
public ObservableCollection<UserControl> UserControls { get; set; }
public ICommand AddButtonCommand { get; set; }
public MainWindowViewModel()
{
AddButtonCommand = new DelegateCommand(ClickButton);
UserControls = new ObservableCollection<UserControl>();
}
private void ClickButton()
{
UserControls.Add(new UCTest());
RaisePropertyChanged("UserControls");
}
}
}
我尝试使用带名称的参数添加构造函数 UserControl,但我不知道如何将其与绑定连接。
我的第二件事是使用 UserControl 和 String(带有选项卡名称)创建类,但我无法将带有 UserControl 的字段绑定到 Widdow。
谢谢, 问候。
【问题讨论】:
-
这个问题可以在这里回答stackoverflow.com/a/5651542/9669202
-
你想绑定UCTest的什么属性?
-
@mm8 可以为此使用 UCTest 标签吗?
-
您可以在 UCTest 中添加一个字符串属性并将其绑定到文本框。
标签: c# wpf xaml data-binding user-controls