Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么绑定只能由一个人使用_C#_Wpf - Fatal编程技术网

C# 为什么绑定只能由一个人使用

C# 为什么绑定只能由一个人使用,c#,wpf,C#,Wpf,我有一个usercontrol,看起来像: 以及xaml代码: <UserControl x:Class="Customizing.Views.IpRangeView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x

我有一个usercontrol,看起来像:

以及xaml代码:

<UserControl x:Class="Customizing.Views.IpRangeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:ig="http://schemas.infragistics.com/xaml"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:mvvm="http://www.galasoft.ch/mvvmlight"
             xmlns:range="clr-namespace:Customizing.Views"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300"
             DataContext="{Binding IpRangeVm, Source={StaticResource Locator}}">
    <Grid>
        <ig:ThemeManager.Theme>
            <ig:Office2013Theme StyleMicrosoftControls="True" />
        </ig:ThemeManager.Theme>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TabControl Grid.Row="0" ItemsSource="{Binding Locations}">

            <TabControl.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding Name}" FontSize="16" FontWeight="Bold" />
                </DataTemplate>
            </TabControl.ItemTemplate>

            <TabControl.ContentTemplate>
                <DataTemplate>
                    <ScrollViewer VerticalScrollBarVisibility="Auto">
                        <ItemsControl ItemsSource="{Binding Addresses}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <UniformGrid Columns="2" />
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Border Margin="20,15,20,15" Padding="15,20,15,20">
                                        <range:IpRangeFields Start="{Binding Start}" End="{Binding End}"
                                                             Subnet="{Binding Subnet}" Gateway="{Binding Gateway}">
                                            <i:Interaction.Triggers>
                                                <i:EventTrigger EventName="Error">
                                                    <mvvm:EventToCommand Command="{Binding Path=DataContext.ErrorCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabControl}}}" />
                                                </i:EventTrigger>
                                            </i:Interaction.Triggers>
                                        </range:IpRangeFields>
                                    </Border>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </ScrollViewer>
                </DataTemplate>

            </TabControl.ContentTemplate>
        </TabControl>

    </Grid>
</UserControl>

正如您在图中看到的,只有subnet字段填充了值,为什么与start、end和gateway的绑定不起作用?我做错了什么

<range:IpRangeFields Start="{Binding Start}" End="{Binding End}"
                     Subnet="{Binding Subnet}" Gateway="{Binding Gateway}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Error">
            <mvvm:EventToCommand Command="{Binding Path=DataContext.ErrorCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabControl}}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</range:IpRangeFields>

视图模型和视图绑定到:

using System.Collections.ObjectModel;
using System.Diagnostics;
using Customizing.Models;
using Customizing.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace Customizing.ViewModel
{
    public class IpRangeViewModel : ViewModelBase
    {
        private readonly IDataService _dataService;

        public IpRangeViewModel(IDataService dataService)
        {
            _dataService = dataService;
            _dataService.QueryIpRanges((ranges, error) => { Locations = ranges; });

            ErrorCmd = new RelayCommand(() => { Debug.WriteLine("Error occurs"); });
        }

        public ObservableCollection<LocationRange> Locations { get; set; }
        public RelayCommand ErrorCmd { get; set; }
    }
}
使用System.Collections.ObjectModel;
使用系统诊断;
使用定制模型;
使用定制服务;
使用GalaSoft.MvvmLight;
使用GalaSoft.MvvmLight.Command;
命名空间自定义.ViewModel
{
公共类IpRangeViewModel:ViewModelBase
{
私有只读IDataService(数据服务);
公共IpRangeViewModel(IDataService数据服务)
{
_数据服务=数据服务;
_QueryIpRanges((范围,错误)=>{Locations=ranges;});
ErrorCmd=newrelaycommand(()=>{Debug.WriteLine(“错误发生”);});
}
公共可观测集合位置{get;set;}
公共RelayCommand ErrorCmd{get;set;}
}
}
模型呢

using System.Collections.ObjectModel;

namespace Customizing.Models
{
    public class LocationRange
    {
        public string Name { get; set; }
        public ObservableCollection<IpRange> Addresses { get; set; }
    }
}
使用System.Collections.ObjectModel;
命名空间自定义.Models
{
公共类位置范围
{
公共字符串名称{get;set;}
公共可观测集合地址{get;set;}
}
}
Usercontrol IPRange字段:

<UserControl x:Class="Customizing.Views.IpRangeFields"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:ig="http://schemas.infragistics.com/xaml"
             xmlns:local="clr-namespace:Customizing.Views"
             xmlns:net="clr-namespace:System.Net;assembly=System"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:behaviors="clr-namespace:Customizing.Behaviors"
             xmlns:system="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d"
             x:Name="_parent"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <system:String x:Key="InputMaskIp">000.000.000.000</system:String>
    </UserControl.Resources>
    <Grid DataContext="{Binding ElementName=_parent}">
        <Grid.RowDefinitions>
            <RowDefinition Height="60" />
            <RowDefinition Height="10" />
            <RowDefinition Height="60" />
            <RowDefinition Height="10" />
            <RowDefinition Height="60" />
            <RowDefinition Height="10" />
            <RowDefinition Height="60" />
            <RowDefinition Height="10" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="2.5*" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="Start" VerticalContentAlignment="Center" FontSize="18"
               HorizontalContentAlignment="Center" FontWeight="Bold" />
        <Label Grid.Row="2" Grid.Column="0" Content="End" VerticalContentAlignment="Center" FontSize="18"
               HorizontalContentAlignment="Center" FontWeight="Bold" />
        <Label Grid.Row="4" Grid.Column="0" Content="Subnet" VerticalContentAlignment="Center" FontSize="18"
               HorizontalContentAlignment="Center" FontWeight="Bold" />
        <Label Grid.Row="6" Grid.Column="0" Content="Gateway" VerticalContentAlignment="Center" FontSize="18"
               HorizontalContentAlignment="Center" FontWeight="Bold" />

        <TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="0" Grid.Column="1"
                 FontSize="22" Validation.Error="_ValidationError">
            <Binding Path="Start" ValidatesOnNotifyDataErrors="True" UpdateSourceTrigger="PropertyChanged"
                     NotifyOnValidationError="true">
                <Binding.ValidationRules>
                    <local:IpAddressRule />
                </Binding.ValidationRules>
            </Binding>
            <i:Interaction.Behaviors>
                <behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
            </i:Interaction.Behaviors>
        </TextBox>

        <TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="2" Grid.Column="1"
                 FontSize="22" Validation.Error="_ValidationError">
            <Binding Path="End" ValidatesOnNotifyDataErrors="True" UpdateSourceTrigger="PropertyChanged"
                     NotifyOnValidationError="true">
                <Binding.ValidationRules>
                    <local:IpAddressRule />
                </Binding.ValidationRules>
            </Binding>
            <i:Interaction.Behaviors>
                <behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
            </i:Interaction.Behaviors>
        </TextBox>

        <TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="4" Grid.Column="1"
                 FontSize="22" Validation.Error="_ValidationError">
            <Binding Path="Subnet" ValidatesOnNotifyDataErrors="True" UpdateSourceTrigger="PropertyChanged"
                     NotifyOnValidationError="true">
                <Binding.ValidationRules>
                    <local:IpAddressRule />
                </Binding.ValidationRules>
            </Binding>
            <i:Interaction.Behaviors>
                <behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
            </i:Interaction.Behaviors>
        </TextBox>

        <TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="6" Grid.Column="1"
                 FontSize="22" Validation.Error="_ValidationError">
            <Binding Path="Gateway" ValidatesOnNotifyDataErrors="True" UpdateSourceTrigger="PropertyChanged"
                     NotifyOnValidationError="true">
                <Binding.ValidationRules>
                    <local:IpAddressRule />
                </Binding.ValidationRules>
            </Binding>
            <i:Interaction.Behaviors>
                <behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
            </i:Interaction.Behaviors>
        </TextBox>


    </Grid>
</UserControl>

000.000.000.000
以及背后的代码:

using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Windows;
using System.Windows.Controls;

namespace Customizing.Views
{
    /// <summary>
    ///     Interaction logic for IpRangeFields.xaml
    /// </summary>
    public partial class IpRangeFields : UserControl
    {
        public static readonly DependencyProperty StartProperty = DependencyProperty.Register("Start", typeof (string),
            typeof (IpRangeFields), new PropertyMetadata(null));

        public static readonly DependencyProperty EndProperty = DependencyProperty.Register("End", typeof (string),
            typeof (IpRangeFields), new PropertyMetadata(null));

        public static readonly DependencyProperty SubnetProperty = DependencyProperty.Register("Subnet", typeof (string),
            typeof (IpRangeFields), new PropertyMetadata(null));

        public static readonly DependencyProperty GatewayProperty = DependencyProperty.Register("Gateway",
            typeof (string), typeof (IpRangeFields), new PropertyMetadata(null));

        // Register the routed event
        public static readonly RoutedEvent ErrorEvent =
            EventManager.RegisterRoutedEvent("Error", RoutingStrategy.Bubble,
            typeof(RoutedEventHandler), typeof(IpRangeFields));

        public IpRangeFields()
        {
            InitializeComponent();
        }

        public event RoutedEventHandler Error
        {
            add { AddHandler(ErrorEvent, value); }
            remove { RemoveHandler(ErrorEvent, value); }
        }

        public string Start
        {
            get { return (string) GetValue(StartProperty); }
            set { SetValue(StartProperty, value); }
        }

        public string End
        {
            get { return (string) GetValue(EndProperty); }
            set { SetValue(EndProperty, value); }
        }

        public string Subnet
        {
            get { return (string) GetValue(SubnetProperty); }
            set { SetValue(SubnetProperty, value); }
        }

        public string Gateway
        {
            get { return (string) GetValue(GatewayProperty); }
            set { SetValue(GatewayProperty, value); }
        }

        private void _ValidationError(object sender, ValidationErrorEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(ErrorEvent, sender));
        }

    }

    public class IpAddressRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            IPAddress ip;
            if (!IPAddress.TryParse(value.ToString(), out ip))
            {
                return new ValidationResult(false, "IP address is not valid.");
            }

            return new ValidationResult(true, null);
        }
    }
}
使用系统;
使用系统诊断;
利用制度全球化;
Net系统;
使用System.Windows;
使用System.Windows.Controls;
命名空间自定义.Views
{
/// 
///IpRangeFields.xaml的交互逻辑
/// 
公共部分类IpRangeFields:UserControl
{
公共静态只读DependencyProperty StartProperty=DependencyProperty.Register(“开始”,类型为(字符串),
typeof(IpRangeFields),新的PropertyMetadata(null));
public static readonly dependencProperty EndProperty=dependencProperty.Register(“End”,typeof(string),
typeof(IpRangeFields),新的PropertyMetadata(null));
公共静态只读DependencyProperty SubnetProperty=DependencyProperty.Register(“子网”,类型为(字符串),
typeof(IpRangeFields),新的PropertyMetadata(null));
公共静态只读DependencyProperty GatewayProperty=DependencyProperty.Register(“网关”,
typeof(字符串)、typeof(IpRangeFields)、新PropertyMetadata(null);
//注册路由事件
公共静态只读RoutedEvent ErrorEvent=
EventManager.RegisterRoutedEvent(“错误”),RoutingStrategy.Bubble,
typeof(RoutedEventHandler),typeof(IpRangeFields));
公共IpRangeFields()
{
初始化组件();
}
公共事件RoutedEventHandler错误
{
添加{AddHandler(ErrorEvent,value);}
删除{RemoveHandler(ErrorEvent,value);}
}
公共字符串开始
{
get{return(string)GetValue(StartProperty);}
set{SetValue(StartProperty,value);}
}
公共字符串结束
{
获取{return(string)GetValue(EndProperty);}
set{SetValue(EndProperty,value);}
}
公共字符串子网
{
获取{return(string)GetValue(SubnetProperty);}
set{SetValue(SubnetProperty,value);}
}
公共字符串网关
{
get{return(string)GetValue(GatewayProperty);}
set{SetValue(GatewayProperty,value);}
}
私有void\u ValidationError(对象发送方,validationErrorReventArgs e)
{
RaiseEvent(新路由EventTargets(ErrorEvent,sender));
}
}
公共类IpAddressRule:ValidationRule
{
公共覆盖验证结果验证(对象值,CultureInfo CultureInfo)
{
ip地址ip;
if(!IPAddress.TryParse(value.ToString(),out ip))
{
返回新的ValidationResult(false,“IP地址无效”);
}
{Binding DataContext.Start,
            RelativeSource={RelativeSource Mode=FindAncestor, 
                                        AncestorType=ListBoxItem}}
<UserControl x:Name="uc">
<StackPanel Orientation="Horizontal">
  <Image Source="{Binding Source={x:Static helper:ImageHelper.JumpLabelImage}}" Width="16" Height="16" VerticalAlignment="Center"/>
  <TextBlock >
    <Hyperlink Command="{Binding ElementName=uc, Path=JumpCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
               CommandParameter="{Binding ElementName=uc, Path=CommandParameter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
        <TextBlock Text="{Binding ElementName=uc, Path=LabelText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" VerticalAlignment="Center" />
    </Hyperlink>
  </TextBlock>
</StackPanel>
</UserControl>
<UserControl x:Class="Customizing.Views.IpRangeFields"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:ig="http://schemas.infragistics.com/xaml"
         xmlns:local="clr-namespace:Customizing.Views"
         xmlns:net="clr-namespace:System.Net;assembly=System"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:behaviors="clr-namespace:Customizing.Behaviors"
         xmlns:system="clr-namespace:System;assembly=mscorlib"
         mc:Ignorable="d"
         x:Name="Uc"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <system:String x:Key="InputMaskIp">000.000.000.000</system:String>
</UserControl.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="60" />
        <RowDefinition Height="10" />
        <RowDefinition Height="60" />
        <RowDefinition Height="10" />
        <RowDefinition Height="60" />
        <RowDefinition Height="10" />
        <RowDefinition Height="60" />
        <RowDefinition Height="10" />
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="2.5*" />
    </Grid.ColumnDefinitions>

    <Label Grid.Row="0" Grid.Column="0" Content="Start" VerticalContentAlignment="Center" FontSize="18"
           HorizontalContentAlignment="Center" FontWeight="Bold" />

    <TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="0" Grid.Column="1"
             FontSize="22" Validation.Error="_ValidationError"
             Text="{Binding ElementName=Uc, Path=Start, ValidatesOnNotifyDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
      </TextBox>

</Grid>
</UserControl>
<range:IpRangeFields Start="{Binding MyStart}" End="{Binding End}"
                     Subnet="{Binding Subnet}" Gateway="{Binding Gateway}"/>