【问题标题】:Change content of UserControl from Page code behind从后面的页面代码更改 UserControl 的内容
【发布时间】:2018-05-28 17:53:08
【问题描述】:

所以我有一个用户控件:

<StackPanel Orientation="Vertical"
                Margin="10">
        <StackPanel Orientation="Horizontal"
                    HorizontalAlignment="Stretch"
                    Margin="10">
            <TextBlock Text="{x:Bind FileName, Mode=OneTime}"
                       HorizontalAlignment="Left"/>
            <TextBlock Text="{x:Bind DownloadSpeed, Mode=OneWay}" 
                       HorizontalAlignment="Right"/>
        </StackPanel>

        <ProgressBar Name="PbDownload"
                     HorizontalAlignment="Stretch" />

        <TextBlock Text="{x:Bind DownloadCompletePercent, Mode=OneWay}"/>

    </StackPanel>

后面的用户控制代码:

public sealed partial class UCDownloadCard : UserControl
    {
        public UCDownloadCard()
        {
            this.InitializeComponent();
        }

        public string FileName { get; set; }
        public string DownloadSpeed { get; set; }
        public string DownloadCompletePercent { get; set; }
    }

我正在尝试使用此用户控件显示文件下载状态。每当开始新的下载时,我想以编程方式添加一个新的用户控件,然后在下载发生时更新其中的值。

目前我正在做这样的事情:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    public CancellationTokenSource CancellationTokenSource { get; set; }
    public List<DownloadOperation> ActiveDownloads { get; set; } = new List<DownloadOperation>();
    public List<UCDownloadCard> AddedCards { get; set; } = new List<UCDownloadCard>();


    private async Task HandleDownloadAsync(DownloadOperation downloadOperation, CancellationToken cancellationToken = new CancellationToken())
    {
        ActiveDownloads.Add(downloadOperation);
        ...
        ...

        try
        {
            AddDownloadProgressCard();
            await downloadOperation.StartAsync().AsTask(CancellationTokenSource.Token, progressCallback);                
        }

        finally
        {
            ...
            ...
        }
    }

    private void AddDownloadProgressCard()
    {
        var card = new UCDownloadCard
        {
            Name = $"Card{AddedCards.Count}",
            FileName = "Filename.pdf",
            DownloadCompletePercent = "0% completed",
            DownloadSpeed = "0 KB/s"
        };

        AddedCards.Add(card);
        OutputArea.Children.Add(card);
    }

    private void DownloadProgressChanged(DownloadOperation downloadOperation)
    {   
        var downloadPercent = 100 * ((double)downloadOperation.Progress.BytesReceived / (double)downloadOperation.Progress.TotalBytesToReceive);
        this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
        {
            AddedCards[0].DownloadCompletePercent = downloadPercent.ToString();
            Debug.WriteLine($"Updating Progress: {downloadPercent}%");
        });

    }    
}

我可以将 UserControl 添加到 OutputArea,但其中的值没有更新。但我确信AddedCards[0].DownloadCompletePercent = downloadPercent.ToString(); 正在执行多次,因为它正下方的Debug.WritLine 实际上正在打印到输出窗口。

如何更新 UserControl 中的值?

【问题讨论】:

  • 您应该在后面的代码中实现“INotifyPropertyChanged”。您的问题是您可能会更改代码中的值,但 UI 没有收到应该更新其值的通知。

标签: c# xaml uwp


【解决方案1】:

首先,您应该将 UserControl 更改为 x:Bind Mode=TwoWay。有关详细信息,请参阅 {x:Bind} markup extension

那么你应该实现INotifyPropertyChanged接口并实现PropertyChanged事件。代码可以参考PropertyChanged事件。

这是一个简单的示例,您可以参考一下。

UserControl.xaml,

<StackPanel Orientation="Vertical"
            Margin="10">
    <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Stretch"
                Margin="10">
    <TextBlock Text="{x:Bind DownloadCompletePercent, Mode=TwoWay}"/>
</StackPanel>

UserControl.xaml.cs,

public sealed partial class UCDownloadCard : UserControl, INotifyPropertyChanged
    {
        public UCDownloadCard()
        {
            this.InitializeComponent();
        }
        private string downloadCompletePercent;
        public string DownloadCompletePercent
        {
            get
            {
                return downloadCompletePercent;
            }
            set
            {
                downloadCompletePercent = value;
                RaisePropertyChanged("DownloadCompletePercent");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }

然后你可以添加这个 UserControl 并更新它的downloadCompletePercent

在 MainPage.xaml.cs 中,

private void DownloadProgress(DownloadOperation obj)
{
    BackgroundDownloadProgress currentProgress = obj.Progress;
    double percent;
    if (currentProgress.TotalBytesToReceive > 0)
    {
        percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
        Debug.WriteLine(percent);
        uCDownloadCard.DownloadCompletePercent = percent.ToString();
    }
}

UCDownloadCard uCDownloadCard;
private void Button_Click_2(object sender, RoutedEventArgs e)
{
    uCDownloadCard = new UCDownloadCard();
    MainPagePanel.Children.Add(uCDownloadCard);
}

【讨论】:

  • 谢谢。不过我需要Mode=OneWay
猜你喜欢
  • 2010-09-05
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多