gpt4 book ai didi

wpf - 关于 WPF MVVM 和用户控件的菜鸟问题

转载 作者:行者123 更新时间:2023-12-04 18:18:59 37 4
gpt4 key购买 nike

我正在开始使用 WPF,并且在实现数据绑定(bind)时遇到了一些困难。

具体来说,我创建了一个简单的用户控件,其中包含一个标签和一个按钮。
对于这个用户控件,我创建了一个仅包含两个属性的 ViewModel,string “文字”和SimpleEnum “地位”。

控件的重点是显示某物的状态,例如“已连接”是/否等。按钮的背景颜色表示状态。

我的 XAML 看起来像这样

<Control.DataContext>
<vm:OnOffStatusViewModel />
</Control.DataContext>

<Label x:Name="label1" Height="Auto" HorizontalAlignment="Left" Content="{Binding Text}" Width="280" />
<Button Style="{StaticResource GlassButton}" Height="14" Width="14" Background="{Binding Status}" Grid.Column="1" />

xmlns:vm="clr-namespace:Controls"
代码隐藏有一个属性 ViewModel暴露 View 模型,实现 INotifyPropertyChanged,初始化为 _viewModel = (OnOffStatusViewModel) DataContext;
现在,在我使用此控件的 View 中,我已设法将 Text 设置为某些内容,因为我在实现 View 代码隐藏中有 onOffStatus1.ViewModel.Text = ... ,但是,状态是由枚举设置的,因此不能真正绑定(bind)到按钮的背景属性。

我与此相关的问题:
  • 我进行控制的方式是否正确?如果不是,在用户控件中实现数据绑定(bind)的正确方法是什么?
  • 如何让我的枚举状态使用绑定(bind)更新按钮的背景属性?
  • 最佳答案

    How can I have my enum status update the background property of the button using binding?



    建议使用 value converter对于此任务,为枚举的每个可能值返回一个画笔。这样,您的 View 模型不需要了解任何关于颜色或画笔的信息,并且您可以在任何您想可视化状态的地方使用转换器。

    XAML
    <UserControl x:Class="WpfApplication1.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1">

    <UserControl.Resources>
    <local:StatusColorConverter x:Key="StatusColorConverter" />
    </UserControl.Resources>

    <Button Background="{Binding Status, Converter={StaticResource StatusColorConverter}" />

    </UserControl>

    转换器
    public enum Status
    {
    Connected
    }

    public class StatusColorConverter : IValueConverter
    {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
    switch ((Status)value)
    {
    case Status.Connected: return new SolidColorBrush(Colors.Green);
    }

    return new SolidColorBrush(Colors.Black);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
    throw new NotImplementedException();
    }
    }

    Is the way I have done the control correct? If not, what is the proper way of implementing data binding in user controls?



    你的实现对我来说似乎很好。您可能希望通过依赖注入(inject)消除 View 模型和 View (当前持有对 View 模型的引用)之间的耦合。但这取决于您的用例和您要使用的架构。

    关于wpf - 关于 WPF MVVM 和用户控件的菜鸟问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089895/

    37 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com