将页面作为ScrollViewer或ContentControl等的内容



是否有方法将Page放入<Grid/>,<StackPanel/>,<ContentControl/><ScrollViewer/>作为使用构造函数调用的代码内容?

我期待这样的事情:

XAML:

<Grid>
<ScrollViewer Content="{Binding Panel0}"/>
</Grid>

c#:

public class TestWindowViewModel : Page
{
public string Name { get; private set; }
public string Description { get; private set; }
public TestWindowViewModel(string name, string description)
{
Name = name;
Description = description;
}
}

_

public partial class SomeViewModel : Page
{
public TestWindowViewModel Panel0;
public SomeViewModel()
{
Panel0 = new TestWindowViewModel("panelName", "panelDescription"); 
InitializeComponent();
}
}

可以使用Frame标签

<ScrollViewer>
<Frame content = "{Binding MyPage}"/>
</ScrollViewer>

如果你不想在你的ViewModel中有一个道具那么你应该可以这样做

<ScrollViewer>
<Frame>
<Frame.Content>
<locals:MyPage>
</Frame.Content>
</ScrollViewer>

记住你有一个叫做TestWindowViewModel的东西,它继承了Page。这不是一个ViewModel。相反,它是一个正常的页面。

你想要看起来像这样:

public class NotifyPropertyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Page myPage;
public Page MyPage
{
get { return myPage; }
set
{
myPage = value;
NotifyPropertyChanged();
}
}
}

,你可以更进一步,创建一个抽象类:

public abstract class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

然后你可以像这样继承ViewModel

public class TestWindow: Page
{
public TestWindow()
{
InitializeComponent();
}
}
public class TestWindowViewModel : ViewModel
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged();
}
}
private string description;
public string Description
{
get { return description; }
set
{
Description = value;
NotifyPropertyChanged();
}
}
}

一旦你得到这一切正确分离出来,你可以使用框架和做同样的SomePage和SomePageViewModel,然后你可以使用实际的框架内容从ViewModel绑定。我知道这是冗长的,但是如果你开始设置一个好的MVVM设置,你将省去你自己的头痛,如果你曾经使用Async和其他不。

在xaml:

<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Frame x:Name="CurrentPage" NavigationUIVisibility="Hidden"></Frame>
</ScrollViewer>

在cs:

CurrentPage.Content = content;

内容为Page

最新更新