XAML:从不同的命名空间将视图绑定到ViewModel

时间:2018-06-08 00:37:33

标签: c# xaml uwp

我确定这是一个基本问题,但我无法弄清楚如何做到这一点。我在一个名称空间中有一个View,在另一个名称空间中有ViewModel。我如何将这两者绑在一起?

My View位于MyProject.View的命名空间中。我的ViewModel位于MyProject.ViewModel的名称空间中。

如何在XAML中绑定它?我在UWP中这样做,但无论UWP / WPF / X.Forms如何,我都认为这是相同的。

<Page
  x:Class="MyProject.View.MainPage"
  xmlns:vm="using:MyProject.ViewModel"
  DataContext="{Binding MainPageViewModel, Source={StaticResource vm:MainPageViewModel}}"

2 个答案:

答案 0 :(得分:1)

根据您的说明,我已经提供了一个代码示例供您参考:

enter image description here

public class MainViewModel:INotifyPropertyChanged
{
    private string _Name;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            RaisePropertyChanged("Name");
        }
    }

    public MainViewModel()
    {
        this.Name = "Hello UWP!";
    }

    private void RaisePropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
        }
    }
}
<Page
x:Class="AppViewModel.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppViewModel"
xmlns:vm="using:AppViewModel.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Page.DataContext>
    <vm:MainViewModel></vm:MainViewModel>
</Page.DataContext>
<Grid>
    <TextBlock Text="{Binding Name}"></TextBlock>
</Grid>

答案 1 :(得分:0)

我认为你想做那样的事情:

<Page x:Class="MyProject.View.MainPage" 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:VM="clr-namespace:MyProject.ViewModels">

    <Page.BindingContext>
        <VM:MainPageViewModel />
    </Page.BindingContext>

    <!-- content here -->

</Page>

每次创建新MainPageViewModel时,都会为MainPage创建一个新实例。

相关问题