ListView DataTemplate内部UserControl无法绑定

时间:2019-03-11 02:38:12

标签: wpf listview data-binding user-controls datatemplate

我有这个问题:

我在表单中有一个ListView控件。 CustomControl的{​​{1}}中有一个DataTemplate。我希望将此自定义控件绑定到当前窗体的ViewModel中的Time属性,但是不能绑定,但是可以绑定中间的ListView其他控件,这是怎么回事?我将非常感激

这是我的窗口:

DataTemplate

这是我的CustomControl <ListView Grid.Row="2" ItemsSource="{Binding PlanRotation}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Margin="20 0 0 0" Orientation="Horizontal"> <TextBlock HorizontalAlignment="Center" Text="时间:" VerticalAlignment="Center" FontWeight="Bold" /> <TimeControl:DateTimePicker Tag="{Binding ElementName=myWin,Path=DataContext.Time,Mode=OneWayToSource}" HorizontalAlignment="Center" Height="28" VerticalAlignment="Center" Width="152" Foreground="White" BorderThickness="1" BorderBrush="#FFABADB3" Background="Black" Grid.Column="1"/> <ComboBox Text="{Binding ElementName=myWin,Path=DataContext.Scenes,Mode=OneWayToSource}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="80" Height="21"> </ComboBox> 代码:

TimeControl:DateTimePicker

我的自定义控件的 <UserControl x:Class="ManagementProject.UserControls.TimeControl.DateTimePicker" 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:local="clr-namespace:ManagementProject.UserControls.TimeControl" xmlns:myTime="clr-namespace:ManagementProject.UserControls.TimeControl" xmlns:sys="clr-namespace:System;assembly=mscorlib" mc:Ignorable="d" d:DesignHeight="25" d:DesignWidth="150" Width="150" MaxHeight="25" x:Name="dtpName" Loaded="UserControl_Loaded" Tag="{Binding ElementName=textBlock1, Path=Text}"> <TextBox Height="23" HorizontalAlignment="Left" Text="{Binding ElementName=dtpName,Path=Tag,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}" Margin="4,3,0,0" Name="textBlock1" VerticalAlignment="Top" Width="123" Foreground="White" Background="{x:Null}" BorderBrush="{x:Null}" SelectionBrush="{x:Null}" Style="{DynamicResource TextBoxStyle1}" /> 的文本是在后台分配的。

1 个答案:

答案 0 :(得分:0)

在初始化用户控件时,我只能直接绑定它。我最终创建了一个依赖项属性,以便能够从其外部更新用户控件。

internal List<User> ContactlistContainer
        {
            get => (List<User>)GetValue(ContactlistContainerProperty);
            set => SetValue(ContactlistContainerProperty, value);
        }

internal static readonly DependencyProperty ContactlistContainerProperty =
                DependencyProperty.Register("ContactlistContainerProperty", typeof(List<User>), typeof(User), new PropertyMetadata(new List<User>()));