我正在使用 MVVM light 创建我的第一个 C# UWP 桌面应用程序,但我在内存使用和数据模板方面遇到了小问题。 在 Button.cs 中,有一个 ObservableCollection 可能有不同的对象(IExample),例如:圆形、正方形和其他... 根据该集合中的内容,应显示正确的 UI。
这是我的代码:
按钮.cs:
using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;
namespace MvvmLight1.Model
{
public class Button : ObservableObject
{
public string Name { get; set; }
public const string InternalObjectsPropertyName = "InternalObjects";
private ObservableCollection<IExample> _internalObjects = null;
public ObservableCollection<IExample> InternalObjects
{
get
{
return _internalObjects;
}
set
{
if (_internalObjects == value)
{
return;
}
_internalObjects = value;
RaisePropertyChanged(InternalObjectsPropertyName);
}
}
public Button()
{
InternalObjects = new ObservableCollection<IExample>();
}
}
}
MainPage.xaml:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MvvmLight1"
xmlns:ignore="http://www.galasoft.ch/ignore"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:local1="using:MvvmLight1.Model"
x:Class="MvvmLight1.MainPage"
mc:Ignorable="d ignore"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Page.Resources>
<!-- template for circle -->
<DataTemplate x:Key="CircleTemplate">
<StackPanel>
<TextBlock Text="This is the template for circle..." Foreground="Crimson" HorizontalAlignment="Center"></TextBlock>
<ColorPicker x:Name="myColorPicker" ColorSpectrumShape="Ring"/>
</StackPanel>
</DataTemplate>
<!-- template for square -->
<DataTemplate x:Key="SquareTemplate">
<StackPanel>
<TextBlock Text="This is the template for square..." Foreground="Green" HorizontalAlignment="Center"></TextBlock>
<ColorPicker x:Name="myColorPicker" ColorSpectrumShape="Ring"/>
</StackPanel>
</DataTemplate>
<local1:TemplateSelector x:Key="MySelector"
CircleTemplate="{StaticResource CircleTemplate}"
SquareTemplate="{StaticResource SquareTemplate}"
/>
</Page.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- buttons -->
<GridView ItemsSource="{Binding ButtonsList}" Grid.Row="0" SelectedItem="{Binding SelectedButton, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Foreground="Red"
FontSize="15" Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<!-- properties -->
<ItemsControl ItemsSource="{Binding InternalObjects, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemTemplateSelector="{StaticResource MySelector}" DataContext="{Binding SelectedButton}" Grid.Column="1"></ItemsControl>
</Grid>
public class MainViewModel : ViewModelBase
{
public const string ButtonsListPropertyName = "ButtonsList";
private ObservableCollection<Button> _buttonsList = null;
public ObservableCollection<Button> ButtonsList
{
get
{
return _buttonsList;
}
set
{
if (_buttonsList == value)
{
return;
}
_buttonsList = value;
RaisePropertyChanged(ButtonsListPropertyName);
}
}
public const string SelectedButtonPropertyName = "SelectedButton";
private Button _selectedButton = null;
public Button SelectedButton
{
get
{
return _selectedButton;
}
set
{
if (_selectedButton == value)
{
return;
}
_selectedButton = value;
RaisePropertyChanged(SelectedButtonPropertyName);
}
}
public MainViewModel()
{
ButtonsList = new ObservableCollection<Button>();
// create new buttons
for (var i = 0; i < 12; i++)
{
ButtonsList.Add(new Button());
}
// for few of them add circles...
for (var i = 0; i < 3; i++)
{
ButtonsList[i].Name = "Button with Circle";
ButtonsList[i].InternalObjects.Add(new Circles() { Name = "Circles" });
}
// for another add squares...
for (var i = 3; i < 6; i++)
{
ButtonsList[i].Name = "Button with Squres";
ButtonsList[i].InternalObjects.Add(new Squares() { Name = "Squares" });
}
// rest of them mixed...
for (var i = 6; i < 12; i++)
{
ButtonsList[i].Name = "Button with Circles and Squres";
ButtonsList[i].InternalObjects.Add(new Circles() { Name = "Circles" });
ButtonsList[i].InternalObjects.Add(new Squares() { Name = "Squares" });
}
}
}
Circles.cs:
public class Circles : IExample
{
public string Name { get; set; }
}
Squares.cs:
public class Squares : IExample
{
public string Name { get; set; }
}
TemplateSelector.cs:
public class TemplateSelector : DataTemplateSelector
{
public DataTemplate CircleTemplate { get; set; }
public DataTemplate SquareTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item)
{
if (item.GetType() == typeof(Circles))
{
return CircleTemplate;
}
else if (item.GetType() == typeof(Squares))
{
return SquareTemplate;
}
else
{
return null;
}
}
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
return SelectTemplateCore(item);
}
}
我做错了什么?为什么内存从 19mb 增长到 91mb?
[编辑]: 完整的解决方案在这里:download
最佳答案
每次您选择按钮时,DataTemplateSelector 都会从圆形和方形模板创建新的控件。我可以通过将模板添加到 ItemsControl 的资源并在每次更新 InternalObjects-Collection 时创建/处置控件来避免这种情况:
<ItemsControl ItemsSource="{Binding InternalObjects, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding SelectedButton}" Grid.Column="1">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type local:Circles}">
<TextBlock Text="This is the template for a circle too..." Foreground="Crimson" HorizontalAlignment="Center"></TextBlock>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Squares}">
<TextBlock Text="This is the template for a square too..." Foreground="Crimson" HorizontalAlignment="Center"></TextBlock>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
使用 ComboBox 进行测试:
<ComboBox ItemsSource="{Binding ButtonsList}" Grid.Row="0" SelectedItem="{Binding SelectedButton, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemTemplate>
<DataTemplate DataType="x:String">
<TextBlock Text="{Binding Name}" Foreground="Red" FontSize="15" Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
根据模板的大小,它可能仍会消耗大量内存。
要考虑的另一个选项是从模板中提取控件并创建它的单个实例(如果可能,例如 ColorPicker)。
否则您需要依赖 C#/UWP 来为您管理创建的控件。
关于C# UWP DataTemplate 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876432/