我正在尝试制作一个在WPF应用程序中使用的自定义标题栏,部分原因是为了学习/练习使用用户控件。我已经完成了我认为需要做的事情,将用户控件视图模型中的命令绑定到主窗口的属性( windowstate )并按下按钮,但是尽管当按钮被按下时命令正在执行,包含用户控件的主窗口的窗口状态并没有改变。
关于这里的绑定,有什么我不理解的地方吗?我觉得我已经完全按照我能在网上找到的所有说明去做了!(显然我没有)
下面是用户控件xaml:
<UserControl x:Class="UserControls.TitleBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:ViewModels"
mc:Ignorable="d">
<UserControl.DataContext>
<vm:TitleBar_ViewModel/>
</UserControl.DataContext>
<Button Command="{Binding MaximiseCommand}" />
</UserControl>视图模型中的代码如下所示:
namespace ViewModels
{
public class TitleBar_ViewModel : DependencyObject, INotifyPropertyChanged
{
public TitleBar_ViewModel() { }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private WindowState _windowState;
public WindowState WindowState
{
get
{ return _windowState; }
set
{
_windowState = value;
OnPropertyChanged();
}
}
private ICommand _maximiseCommand;
public ICommand MaximiseCommand
{
get
{
if (_maximiseCommand == null)
{
_maximiseCommand = new RelayCommand(param => this.Maximise(), param => true);
}
return _maximiseCommand;
}
}
private void Maximise()
{
WindowState = WindowState.Maximized;
}
}
}使用用户控件的主窗口的xaml如下:
<Window x:Class="Demo.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:uc="clr-namespace:UserControls;assembly=UserControls"
mc:Ignorable="d"
WindowState="{Binding WindowState,ElementName=Titlebar}">
<Grid>
<uc:TitleBar x:Name="Titlebar"/>
</Grid>
</Window>对于这个演示,我已经尽可能地保持简单,所以希望你能给出一些我遗漏的构建过程中的一些重要部分,这些部分会导致主窗口状态不受按钮按下的影响。
任何指针都很棒;这种用户控件的使用真的让我大吃一惊,我真的想开始使用它来避免为每个应用程序一遍又一遍地复制代码!
发布于 2019-06-25 19:50:24
您的Usercontrol没有WindowState属性,但它的DataContext属性。所以:
WindowState="{Binding DataContext.WindowState,ElementName=Titlebar}"https://stackoverflow.com/questions/56753253
复制相似问题