使用用户控件或MVVM后面的代码

时间:2014-06-07 12:29:37

标签: c# wpf mvvm user-controls

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

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文件名Window.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,但我觉得在这种情况下它是不必要的,只会使代码更复杂。

2 个答案:

答案 0 :(得分:0)

Fist创建ViewMOdel类

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";
     }

答案 1 :(得分:0)

稍微分开:

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();
            });
        }
    }
}

警报的视图模型

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;
}