我有一個下載器,它有一個進度屬性,它是:不能綁定到自己的依賴屬性
public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register("Progress", typeof(int), typeof(Downloader), new PropertyMetadata(0, new PropertyChangedCallback(OnProgressChange)));
public int Progress
{
get { return (int)this.GetValue(ProgressProperty); }
private set { this.SetValue(ProgressProperty, value); }
}
private static void OnProgressChange(DependencyObject @object, DependencyPropertyChangedEventArgs e)
{
Downloader d = @object as Downloader;
if (d.PropertyChanged != null) d.PropertyChanged(d, new PropertyChangedEventArgs("Progress"));
}
當我嘗試使用它在其他類XAML(m_downloader是下載的私人領域類型):
<sdk:Label Height="24" HorizontalAlignment="Left" Margin="360,12,0,0" Name="ProgressLabel" VerticalAlignment="Top" Width="38" Content="{Binding Path=m_downloader.Progress, StringFormat='\{0\} %'}" />
沒有任何反應。在調試期間,我可以看到d.PropertyChanged始終爲空。如何使它在標籤中顯示進度?
編輯1:
m_downloader這樣的工作(臨時更改後屬性):
public partial class AudioPlayer : UserControl
{
public AudioPlayer()
{
m_downloader = new Downloader();
InitializeComponent();
}
...
public Downloader m_downloader {get; private set;}
}
編輯2:
我已經做了在Blend的結合,它將xaml更改爲:
<UserControl x:Name="audioPlayer" x:Class="Media.Controls.AudioPlayer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="125" d:DesignWidth="410" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White">
...
<sdk:Label Height="24" HorizontalAlignment="Left" Margin="337,12,0,0" Name="ProgressLabel" VerticalAlignment="Top" Width="61" Content="{Binding m_downloader.Progress, ElementName=audioPlayer, Mode=OneWay}" />
...
</Grid>
</UserControl>
爲什麼將ElementName設置爲名稱嵌套,而不是嵌套的?這對我來說沒有意義......但是它在這個變化之後起作用。
如果m_downloader是私人的,你不能綁定到它。它需要公開。 –
我改爲公開,但仍然沒有運氣...... – deha
你確定,DataContext設置正確,所以你可以綁定到m_downloader? – Euphoric