WPF PropertyDependency 绑定到不同类型

发布于 2025-01-17 04:03:12 字数 1298 浏览 2 评论 0原文

在此处键入

userControl 代码

        public double Version
        {
            get { return (double)GetValue(VersionProperty); }
            set
            {
                SetValue(VersionProperty, value);
                SetValue(Version_StringProperty, $"Ver{value:0.00}");
            }
        }

        public string Version_String
        {
            get { return (string)GetValue(Version_StringProperty); }
            set
            {
                SetValue(Version_StringProperty, value);
            }
        }

        public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(double), typeof(MachineVersionObject));
        
        public static readonly DependencyProperty Version_StringProperty = DependencyProperty.Register("Version_String", typeof(string), typeof(MachineVersionObject));

XAML

<TextBlock Text="{Binding Path=Version_String, ElementName=maachineVersion, UpdateSourceTrigger=PropertyChanged}" FontSize="15" Foreground="#F1F1F1" FontWeight="Bold"
                               Margin="2 3 2 0" />

如何将双精度类型绑定到依赖属性字符串或将 Version 属性传递到 Version_string 属性?

我尝试将版本属性直接绑定到文本块,它显示了值 “1.36”“2”“2.5”

但我想在前面添加一个“Ver”并使值显示全部2个小数位。

type here

userControl code

        public double Version
        {
            get { return (double)GetValue(VersionProperty); }
            set
            {
                SetValue(VersionProperty, value);
                SetValue(Version_StringProperty, 
quot;Ver{value:0.00}");
            }
        }

        public string Version_String
        {
            get { return (string)GetValue(Version_StringProperty); }
            set
            {
                SetValue(Version_StringProperty, value);
            }
        }

        public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(double), typeof(MachineVersionObject));
        
        public static readonly DependencyProperty Version_StringProperty = DependencyProperty.Register("Version_String", typeof(string), typeof(MachineVersionObject));

XAML

<TextBlock Text="{Binding Path=Version_String, ElementName=maachineVersion, UpdateSourceTrigger=PropertyChanged}" FontSize="15" Foreground="#F1F1F1" FontWeight="Bold"
                               Margin="2 3 2 0" />

How do i bind a double type to a dependency property string or pass the Version property to the Version_string property?

I tried binding the Version Property directly to the textblock and it displayed the values
"1.36" "2" "2.5"

But i would like to add a "Ver" in front and make the values displayed all 2 decimal places.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青春如此纠结 2025-01-24 04:03:12

这是一个粗略的草图(我认为)可以满足您的要求。神奇之处在于绑定属性的 setter/getter 方法,它利用 INotifier 中的 Update 方法来更新彼此和 GUI,反之亦然。

我使用了 2 个文本框(首先更改版本号),因为这样制作快速 GUI 更简单,但原则上我认为这就是您正在寻找的:

在此处输入图像描述

.NET 6、Visual Studio WPF应用程序模板:

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance local:ViewModel}"
        Title="MainWindow" Height="75" Width="100">
    <StackPanel>
        <TextBox Text="{Binding VersionNumber}"/>
        <TextBox Text="{Binding VersionString}"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs(注意,ViewModel类应该是它自己的文件):

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

namespace WpfApp1
{

    public class ViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler? PropertyChanged = null;

        protected void Update<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return;

            field = value;
            OnPropertyChanged(propertyName);
        }

        private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChangedEventHandler? handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private string _versionString = "Ver1";
        private string _versionNumber = "1";
        private int _version = 1;
        public string VersionString
        {
            get => _versionString;
            set { Update(ref _versionString, value); }
        }

        public string VersionNumber
        {
            get => _versionNumber;
            set
            {
                _versionNumber = value;
                _version = int.Parse(_versionNumber);
                VersionString = $"Ver{_version}";
            }
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

最终细节,我修改了< code>App.xaml 和 App.xaml.cs 以便将数据上下文正确连接到 gui

xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1">
    <Application.Resources>
         
    </Application.Resources>
</Application>

代码隐藏:

using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App

    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var viewModel = new ViewModel();
            var mainWindow = new MainWindow { DataContext = viewModel };
            mainWindow.Show();
        }
    }
}

Here is a rough sketch that (I think) does what you want. The magic is in the setter/getter method of the bound properties, which utilize the Update method in INotifier to update each other and the GUI and vice versa.

I used 2 text boxes (first changes the version number) because it simpler to make a quick GUI that way, but in principle I think this is what you are looking for:

enter image description here

.NET 6, Visual Studio WPF Application template:

MainWindow.xaml:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance local:ViewModel}"
        Title="MainWindow" Height="75" Width="100">
    <StackPanel>
        <TextBox Text="{Binding VersionNumber}"/>
        <TextBox Text="{Binding VersionString}"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs (note, ViewModel class should be its own file):

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

namespace WpfApp1
{

    public class ViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler? PropertyChanged = null;

        protected void Update<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return;

            field = value;
            OnPropertyChanged(propertyName);
        }

        private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChangedEventHandler? handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private string _versionString = "Ver1";
        private string _versionNumber = "1";
        private int _version = 1;
        public string VersionString
        {
            get => _versionString;
            set { Update(ref _versionString, value); }
        }

        public string VersionNumber
        {
            get => _versionNumber;
            set
            {
                _versionNumber = value;
                _version = int.Parse(_versionNumber);
                VersionString = 
quot;Ver{_version}";
            }
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

Final detail, I modified App.xaml and App.xaml.cs in order to wire the data context to the gui properly

xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1">
    <Application.Resources>
         
    </Application.Resources>
</Application>

Code behind:

using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App

    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var viewModel = new ViewModel();
            var mainWindow = new MainWindow { DataContext = viewModel };
            mainWindow.Show();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文