在我的应用程序中,我使用UserControl实例来显示实现INotifyPropertyChanged的ViewModel的复杂类型的内容,以显示当前后台进程的状态。此ViewModel作为DependencyProperty公开给UserControl。WPF:绑定到单个复杂项目
DependencyProperty设置的很好,事件由ViewModel愉快地发出。但是,似乎WPF的数据绑定让我感到头痛。 (另外,我不会认为自己是WPF的专家;问题及其解决方案可能很简单,但它无法提供给我。)
基本上,我看到的所有内容都是我的UI上的“Initialzing”,它是DependencyProperty的默认值以及用于绑定的回退值。如果我改变DependencyProperty的默认值,UI将显示这些值。如果我删除了DependencyProperty的默认值(即null
),它将使用回退值。
我真正想要的是显示ViewModel的内容。
视图模型:
public class ImportInformation : INotifyPropertyChanged
{
/* ... */
}
用户控制:
public partial class ImportTab : UserControl
{
public static readonly DependencyProperty ValueProperty = DependencyProperty
.Register("ValueProperty", typeof(ImportInformation), typeof(ImportTab), new PropertyMetadata(new ImportInformation { TaskName = "Initializing...", CurrentTask = "Initializing...", Progress = Double.NaN }));
public ImportInformation Value
{
get { return (ImportInformation)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public ImportTab()
{
InitializeComponent();
}
}
XAML:
<UserControl x:Class="LingImp.Tabs.ImportTab"
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:conv="clr-namespace:LingImp.Converters"
mc:Ignorable="d" Name="root"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<conv:NaNConverter x:Key="nanConv"/>
</UserControl.Resources>
<StackPanel Orientation="Vertical">
<TextBlock Padding="0,4,0,4" TextWrapping="Wrap">
Your import is currently being processed. Depending on the data source, this can take a long, <Italic>long</Italic> time.
</TextBlock>
<GroupBox VerticalAlignment="Top" HorizontalAlignment="Left" MinWidth="150" DataContext="{Binding ElementName=root, Path=Value}">
<GroupBox.Header>
<TextBlock FontWeight="Bold" Text="{Binding Path=TaskName, Mode=OneWay, FallbackValue=Initializing...}"/>
</GroupBox.Header>
<StackPanel Orientation="Vertical" Margin="4">
<TextBlock TextWrapping="Wrap" Text="{Binding Path=CurrentTask, Mode=OneWay, FallbackValue=Initializing...}"
Margin="0,0,0,2"/>
<ProgressBar MinHeight="9" HorizontalAlignment="Stretch" Minimum="0" Maximum="1"
IsIndeterminate="{Binding Path=Progress, Mode=OneWay, FallbackValue=true, Converter={StaticResource nanConv}}"
Value="{Binding ElementName=root, Path=Value.Progress, Mode=OneWay, FallbackValue=0}"/>
<TextBlock FontSize="11" HorizontalAlignment="Right"
Text="{Binding Path=Progress, Mode=OneWay, FallbackValue=0, StringFormat=\{0:P\}}"/>
</StackPanel>
</GroupBox>
</StackPanel>
</UserControl>
1.在'ImportInformation'中您的setter是否引发'PropertyChanged'事件? 2.你如何更新你的ImportInformation? 3. Visual Studio的“输出”窗口是否显示任何绑定错误? – Heinzi 2010-06-28 09:01:05
对不起,如果我跳过那门课。我认为这将是太长和无聊发布:-)但是,当另一个后台线程设置它的值时,事件被正确触发。但我注意到,没有人订阅了PropertyChanged事件,所以我的猜测是问题在于我的XAML代码片段。 – Manny 2010-06-28 09:07:58