使用用户控件或MVVM的代码

本文关键字:MVVM 代码 控件 用户 | 更新日期: 2023-09-27 18:07:30

首先,这里是一些工作代码:

MyUserControl.xaml中,我将DataContext="{Binding RelativeSource={RelativeSource Self}}"设置在UserControl块中。在我的代码中,我有

<Label Content="{Binding Header}" /> 

我认为很明显,Header是在文件MyUserControl.xaml.cs后面的代码像这样:public string Header { get; set; }。除了这个属性,还有一个函数使用户控件可见:

public object Show(string messageBoxText, string caption, string button)
{
    Header = caption;
    this.Visibility = Visibility.Visible;
    return "test";
}

一切正常。在我的应用程序中,我想使用这个,我把它添加到我的。xaml文件名窗口。xaml:

<t:MessageBox x:Name="nBox"/>

这允许我使用这个:

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    testButton.Content = nBox.Show("1", "1", "1")
End Sub

我想知道的是,像这样设计用户控件是个好主意吗?我的意思是,它给了我的能力,只是调用.Show在我的用户控制,使它可见,并发送所需的东西,我需要。我试图实现MVVM,但我有感觉,这是不必要的,在这种情况下,只会使代码更复杂。

使用用户控件或MVVM的代码

再多一点分隔:

MainViewModel

class MainViewModel : Mvvm.ViewModel
{
    private Alert _pageAlert = null;
    public Alert PageAlert { get { return this._pageAlert; } set { this._pageAlert = value; this.PropertyChange("PageAlert"); } }
    public Mvvm.Command ShowAlert
    {
        get
        {
            return new Mvvm.Command(() =>
            {
                this.PageAlert = new Alert();
                this.PageAlert.Show();
            });
        }
    }
}

Alert's View Model

public class Alert
{
    private bool _isVisible = false;
    public bool IsVisible { get { return this._isVisible; } set { this._isVisible = value; PropertyChanged("IsVisible"); }
    public string Message { get; set; }
    public string Header { get; set; }
    public Uri Image { get; set; } 
    public string ButtonCaption { get; set; }
    #if (DEBUG)
    public Alert()
    {
        this.Header = "Alert";
        this.ButtonCaption = "OK";
        this.Image = new Uri("http://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png");
        this.Message = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    }
    #endif
    public Alert(string Header, string Message, string ButtonCaption, Uri Image)
    {
        this.Header = Header;
        this.Message = Message;
        this.ButtonCaption = ButtonCaption;
        this.Image = Image;
    }
    public Mvvm.Command ButtonClick
    {
        get
        {
            return new Mvvm.Command(() =>
            {
                this.IsVisible = false;
            });
        }
    }
    public void Show()
    {
        this.IsVisible = true;
    }
}

Alert的UserControl

<UserControl
    x:Class="StackOverflow.AlertUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:StackOverflow"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400"
    d:DataContext="{d:DesignInstance Type=local:Alert, IsDesignTimeCreatable=True}">
    <Grid Background="LightGray" Opacity=".95">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="6*" />
            <RowDefinition Height="2*" />
        </Grid.RowDefinitions>
        <!--Header-->
        <Rectangle Fill="Navy" />
        <Rectangle Fill="Gray" Opacity=".25"/>
        <TextBlock Text="{Binding Header}" Grid.Column="1" VerticalAlignment="Center" Margin="5" FontSize="16" />
        <!--Body-->
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="2*" />
                <ColumnDefinition Width="8*" />
            </Grid.ColumnDefinitions>
            <Image Source="{Binding Image}" Margin="15" VerticalAlignment="Top" />
            <TextBlock  Text="{Binding Message}" TextWrapping="Wrap" Margin="10" Foreground="Black" FontSize="14"  Grid.Column="1" />
        </Grid>
        <!--Footer-->
        <Button Grid.Row="2" HorizontalAlignment="Right" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderBrush="Black" Command="{Binding ButtonClick}">
            <TextBlock Text="{Binding ButtonCaption}" Foreground="Black" />
        </Button>
    </Grid>
</UserControl>

和示例主页的使用:

<Page
        x:Class="StackOverflow.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:StackOverflow"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    <Page.DataContext>
        <local:MainViewModel />
    </Page.DataContext>
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.Resources>
            <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
        </Grid.Resources>
        <local:AlertUserControl Height="300" Width="400" DataContext="{Binding PageAlert}" Visibility="{Binding IsVisible, Converter={StaticResource BoolToVisibilityConverter}, FallbackValue=Collapsed}" />
        <Button Content="Show Alert" Command="{Binding ShowAlert}" />
    </Grid>
</Page>

一些简单的实现Mvvm的东西(转换器,命令),以防需要。

public class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return (bool)(value ?? false) ? Visibility.Visible : Visibility.Collapsed;
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return DependencyProperty.UnsetValue;
    }
}

public class Command : ICommand
{
    private Action _commandAction;
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public event EventHandler CanExecuteChanged;
    public void Execute(object parameter)
    {
        _commandAction();
    }
    public Command(Action CommandAction)
    {
        this._commandAction = CommandAction;
    }
}
public class ViewModel : INotifyPropertyChanged
{
    public void PropertyChange(string Property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(Property));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

first Create ViewMOdel class

public class ViewModel:ViewModelBase 

{

  public string Header{get;set;} 
}

然后使用这个类来构造xaml.cs

    public MainWindow()
    {
        InitializeComponent();
        viewModel= new ViewModel();
        this.DataContext = viewModel;
    }
    public ViewModel viewModel{ get; set; }

然后工作你的功能

    public object Show(string messageBoxText, string caption, string button)
    {
         viewModel.Header = caption;
         this.Visibility = Visibility.Visible;
        return "test";
     }