使用MVVM模式从ObservableCollection向WPF添加按钮

本文关键字:WPF 添加 按钮 ObservableCollection MVVM 模式 使用 | 更新日期: 2023-09-27 18:25:10

我正在尝试向UserControl添加按钮。我必须遵循MVVM模式。我创建了一个类DeviceButton,它有不同的set/gets和一个构造函数。在用作数据上下文的视图模型中,是ObservableCollection和该集合的get方法。我已将集合绑定到ItemsControl源,并尝试添加模板。我想我错过了什么,因为按钮无法加载。

UserControl被添加到一个选项卡中(使用dragablz),该选项卡也是ObservableCollection的一部分,也在运行时添加(这很好)。其想法是,该选项卡有一个必须在运行时创建的按钮列表,其中该列表是从web服务中获取的,因此必须动态/编程地添加按钮。Overview只是第一个选项卡——当按钮工作时,每个选项卡的模板(反映提取的项目)都会被实现。目前,我只是在集合中添加一个测试按钮,但如前所述,这不会显示。我错过了什么?

我有一个Overview.xaml文件:

<UserControl // attributes omitted to save spaces... ask if needed>
<StackPanel>
    <Border>
        <TextBlock FontSize="16" FontWeight="Bold" TextWrapping="WrapWithOverflow"
                   TextAlignment="Center" HorizontalAlignment="Center"
                   Foreground="{DynamicResource AccentColorBrush}">
            Welcome to Greenhouse App
        </TextBlock>
    </Border>
    <ItemsControl ItemsSource="{Binding DeviceButtons}">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type vmodel:DeviceButton}">
                <Button Width="50" Height="50" Margin="10 10 0 0" Command="{Binding OpenTab}"
                        CommandParameter="{Binding DeviceType}" HorizontalAlignment="Left"
                        VerticalAlignment="Top" Style="{DynamicResource SquareButtonStyle}">
                    <StackPanel>
                        <Image Source="{Binding ImageUrl}" />
                    </StackPanel>
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    // Manually added test button...
    <Button x:Name="windMill" HorizontalAlignment="Left" Margin="10,0,0,0"
            VerticalAlignment="Top" Width="50" Height="50"
            Command="{Binding OpenTab}" FontFamily="Segoe Ui"
            Style="{DynamicResource SquareButtonStyle}">
        <StackPanel>
            <Image Source="/Greenhouse;component/Icons/Windmill.png" />
        </StackPanel>
    </Button
</StackPanel>

我正在尝试添加DeviceButton类型的ObservableCollection,_deviceButtons集合(作为ItemsSource绑定到ItemsControl)

tabList项目只需查找即可工作,如果需要,我可以手动添加更多(这些项目稍后将通过OpenNewTab命令添加,该命令应绑定到按钮)

DeviceButton文件:

public class DeviceButton
{
    private readonly string _content;
    private readonly string _deviceType;
    private readonly string _imageUrl;
    public DeviceButton(string content, string deviceType, string imageUrl)
    {
        _content = content;
        _deviceType = deviceType;
        _imageUrl = imageUrl;
    }
    public string Content
    {
        get { return _content; }
    }
    public string DeviceType
    {
        get { return _deviceType; }
    }
    public string ImageUrl
    {
        get { return _imageUrl; }
    }
}

集合位于视图模型文件MainWindowViewModel.cs:中

public class MainWindowViewModel : ViewModelBase, INotifyPropertyChanged
{
    public ICommand OpenTab { get; set; }
    private string tabControl { get; set; } = "0";
    private IInterTabClient _interTabClient;
    private ObservableCollection<TabContent> _tabContents = new ObservableCollection<TabContent>();
    private ObservableCollection<DeviceButton> _deviceButtons = new ObservableCollection<DeviceButton>();
    public MainWindowViewModel()
    {
        _interTabClient = new MyInterTabClient();
        DeviceButtons.Add(new DeviceButton("Windturbine", "windturbine", "/Greenhouse;component/Icons/Windmill.png"));
        TabContents.Add(new TabContent("Overview", new Overview()));
        OpenTab = new RelayCommand<object>(OpenNewTab);
    }
    private void OpenNewTab(object obj)
    {
        MessageBox.Show("Yo"); // Not yet implemented
        RaisePropertyChanged(() => tabControl);
    }
    public ObservableCollection<TabContent> TabContents
    {
        get { return _tabContents; }
    }
    public ObservableCollection<DeviceButton> DeviceButtons
    {
        get { return _deviceButtons; }
    }
    public IInterTabClient InterTabClient
    {
        get { return _interTabClient; }
    }
}

当我启动程序时,按钮不会被加载(只有WPF中手动添加的"测试"按钮)。

UserControl,Overview,被认为是另一个Controls中的一个选项卡。Metrowindow,MainWindow.xaml:

<Window.Resources>
    <Style TargetType="{x:Type dragablz:TabablzControl}">
        <Setter Property="CustomHeaderItemTemplate">
            <Setter.Value>
                <DataTemplate DataType="{x:Type viewmodel:TabContent}">
                    <TextBlock Text="{Binding Header}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate DataType="{x:Type viewmodel:TabContent}">
                    <ContentPresenter Margin="4" Content="{Binding Content}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<dragablz:TabablzControl SelectedIndex="{Binding tabControl}" ItemsSource="{Binding TabContents}" x:Name="InitialTabablzControl" Margin="4 0 4 4">
    <dragablz:TabablzControl.InterTabController>
        <dragablz:InterTabController InterTabClient="{Binding MyInterTabClient}" />
    </dragablz:TabablzControl.InterTabController>
</dragablz:TabablzControl>

我想这是Overview.xaml中资源/绑定的问题,但我已经用尽了我能找到的所有建议的解决方案。

使用MVVM模式从ObservableCollection向WPF添加按钮

问题在绑定中

ItemsSource="{Binding Path=DataContext.TabContents, 
              RelativeSource={RelativeSource AncestorLevel=1, 
              AncestorType={x:Type Window}, Mode=FindAncestor}}"

我怀疑DataContext被设置为TabContent对象,该对象没有DeviceButtons属性

我建议使用Snoop这样的工具来验证您的DataContext是否符合您的期望。