我有一个下载器,它有一个进度属性,即:
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 是 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 设置为嵌套的名称,而不是嵌套的名称?这对我来说没有意义......但在这个改变之后它正在工作。