在我的應用程序中,我使用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