c# - 在用户控件或MVVM中使用后面的代码

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

最佳答案

还有一点分离:

主 View 模型

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

警报的 View 模型
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;
    }
}

警报的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;
}

关于c# - 在用户控件或MVVM中使用后面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24097210/

相关文章:

c# - 使用 C# 和 OpenXML 在 xlsx 文件中写入时,Excel 单元格文本被修剪

c# - Web 服务返回空白页而不是 JSON 对象

c# - 转换为可为 null 的枚举

c# - 将单独的 XAML 导入为 ResourceDictionary 并分配 x :Key

WPF 控件移动但其装饰器 - 不是 :"/

c# - WPF:使用 MVVM 时更改数据绑定(bind)

c# - 从字符串到 bool 值的奇怪映射行为

c# - 如何在 WPF 中绑定(bind)用作 DataGridTemplateColumn 的用户控件失败

c# - MVVM 模型到 ViewModel 的通信

.net - MVVM/ViewModels 和处理授权