IP地址文本框用户控件

时间:2014-03-04 16:04:24

标签: wpf binding user-controls textbox ip-address

我正在尝试创建一个充当IP地址持有者的用户控件。 通常,控件由4个TextBox组成,它们一起具有完整的IP地址。 在后面的用户控制代码中有一个公共属性,它保存IPAddress类型的IP地址。 我一直试图公开这个属性,所以我可以将一个属性从我的ViewModel绑定到它。

这是我要公开的用户控件的属性:

public IPAddress IPAddressObject
    {
        get
        {
            return new IPAddress(m_IPAddress);
        }
        set
        {
            m_IPAddress = value.GetAddressBytes();
            NotifyPropertyChanged("Octet1");
            NotifyPropertyChanged("Octet2");
            NotifyPropertyChanged("Octet3");
            NotifyPropertyChanged("Octet4");
        }
    }

它的值正确更新但我无法将值传入我的ViewModel变量Using Binding。 我知道我需要以某种方式使用依赖属性,但我不知道如何将其值与我的属性联系起来。

感谢未来:)

2 个答案:

答案 0 :(得分:0)

比这更容易,你只需要使用一个MaskedInputTextEdit,例如http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox

或选择其中一个。 Where can I find a free masked TextBox in WPF?

Textbox validation for IP Address in WPF

答案 1 :(得分:-3)

我找到了解决方案,问题是我的VM没有正确更新,显然我必须向我的用户控件的DP添加一个特定的元数据,表示它以TwoWay模式绑定。 如下:

        public static readonly DependencyProperty MyCustomProperty =DependencyProperty.Register("MyCustom", typeof(IPAddress), typeof(IPAddressTextBox), new FrameworkPropertyMetadata(IPAddress.Parse("0.0.0.0"), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    public IPAddress MyCustom
    {
        get
        {
            return this.GetValue(MyCustomProperty) as IPAddress;
        }
        set
        {
            this.SetValue(MyCustomProperty, value);
           // NotifyPropertyChanged("MyCustom");
        }
    }