我正在尝试使窗口大小与内容相同,但是当我使用SizeToContent
时,由于某种原因,它会破坏我的EventTrigger
,并且在加载窗口时它不再调用该命令。 / p>
代码示例: 窗口视图:
<Window x:Class="Tasks.Views.TasksWindow"
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:Tasks.Views"
xmlns:ViewModels="clr-namespace:Tasks.ViewModels"
xmlns:Views="clr-namespace:Tasks.Views"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
SizeToContent="WidthAndHeight"
mc:Ignorable="d"
Title="TasksWindow">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadTasksCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Window.DataContext>
<ViewModels:TasksViewModel/>
</Window.DataContext>
<Views:TasksControl/>
</Window>
视图模型:
public class TasksViewModel : ObservableObject
{
private readonly ObservableCollection<TaskModel> _tasks
= new ObservableCollection<TaskModel>();
public IEnumerable<TaskModel> Tasks
{
get { return _tasks; }
}
public ICommand LoadTasksCommand
{
get { return new DelegateCommand(LoadTasks); }
}
public void LoadTasks()
{
string directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string filePath = Path.Combine(directory, "Tasks.xml");
// Check if save file exists
if (!File.Exists(filePath))
return;
XmlSerializer xs = new XmlSerializer(typeof(TaskList));
using (StreamReader reader = new StreamReader("Tasks.xml"))
{
TaskList results = (TaskList)xs.Deserialize(reader);
foreach (var item in results.TasksList)
_tasks.Add(item);
}
}
}
基地:
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
DelegateCommand:
public class DelegateCommand : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action) { _action = action; }
public void Execute(object parameter) { _action(); }
public bool CanExecute(object parameter) { return true; }
public event EventHandler CanExecuteChanged;
}
型号:
[XmlRoot("ArrayOfTaskModel")]
public class TaskList
{
[XmlElement("TaskModel")]
public List<TaskModel> TasksList { get; set; }
}
[Serializable]
public class TaskModel : ObservableObject
{
private string _name;
[XmlElement("Name")]
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChangedEvent("Name");
}
}
}