【问题标题】:Adding buttons to WPF from ObservableCollection using MVVM pattern使用 MVVM 模式从 ObservableCollection 向 WPF 添加按钮
【发布时间】:2015-12-01 15:54:32
【问题描述】:

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

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

我有一个 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 中的资源/绑定的问题,但我已经用尽了所有可以找到的建议解决方案。

【问题讨论】:

  • 我建议使用像 Snoop 这样的工具来验证您的 DataContext 是否符合您的期望...我怀疑 DataContext 被设置为 TabContent 对象,它没有DeviceButtons 财产。
  • 您是否尝试过 ItemsSource="{Binding Path=DataContext.TabContents, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type Window}, Mode=FindAncestor}}"?是的,在这种情况下你应该使用 Snoop。
  • @galakt 谢谢,做到了。如果您确实做出了答案,我会将其标记为正确答案。
  • @Rachel 谢谢,这是一个非常棒的工具,是我一直在寻找的东西。
  • @user2832479 确定答案已发布

标签: c# wpf xaml mvvm dynamically-generated


【解决方案1】:

问题在于绑定

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

【讨论】:

  • 只是一个小评论:我用DataContext.DeviceButtons而不是TabContents
【解决方案2】:

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

我建议使用Snoop 之类的工具来验证您的DataContext 是否符合您的预期。

【讨论】:

  • 我给了你一个赞成票,但我的投票没有公开,因为我自己的声誉还不够高。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-14
  • 2018-01-13
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
相关资源
最近更新 更多