【发布时间】:2015-09-21 15:57:59
【问题描述】:
我有一个需要使用多个命令行参数调用的 wpf 应用程序。出于这个原因,我如何在我放在窗口中的标签中显示它们? 我试图实现数据绑定,但没有成功, - 变量被正确读取和分配,但由于某种荒谬的原因,在我想要的标签中没有显示在屏幕上。 代码如下:
public partial class MainWindow : Window
{
public Notification _notif = new Notification();
public MainWindow()
{
InitializeComponent();
this.DataContext = new Notification();
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
App.Current.Shutdown();
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e){
if (e.Args.Length >= 4)
{
MainWindow mainWindow = new MainWindow();
Label count_label = (Label)mainWindow.FindName("count");
count_label.DataContext = mainWindow._notif;
System.Diagnostics.Debug.WriteLine(mainWindow._notif.count + " - notif.count");
// bind the Date to the UI
count_label.SetBinding(Label.ContentProperty, new Binding("count")
{
Source = mainWindow._notif,
Mode = BindingMode.TwoWay
});
//assigning values to the labels
System.Diagnostics.Debug.WriteLine(count_label.Content + " - content of the label 'count'");
mainWindow._notif.count = e.Args[0];
System.Diagnostics.Debug.WriteLine(e.Args[0] + " is the argument n. 0");
System.Diagnostics.Debug.WriteLine(mainWindow._notif.count + " - notif.count");
System.Diagnostics.Debug.WriteLine(count_label.Content + "-------------------");
System.Diagnostics.Debug.WriteLine(count_label.Content + " - content of the label 'count'");
mainWindow._notif.count = "1234";
System.Diagnostics.Debug.WriteLine(mainWindow._notif.count + " - notif.count");
System.Diagnostics.Debug.WriteLine(count_label.Content + " - content of the label 'count'");
}
}
}
public class Notification : INotifyPropertyChanged
{
private string _count;
public string count {
get {
return _count;
}
set {
_count = value;
OnPropertyChanged("count");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
在这里您可以看到来自 xaml 的 sn-p:
<Label x:Name="count" Content="{Binding count}" HorizontalAlignment="Center" Margin="0,10,486,0" VerticalAlignment="Top" RenderTransformOrigin="-2.895,-0.769" Height="80" Width="145" FontFamily="Arial" FontSize="64" HorizontalContentAlignment="Center"/>
谢谢你。
【问题讨论】:
-
App OnStartUp 方法中的 MainWindow 实例与 App.xaml 中指定的 StartupUri 不同
-
要将 args 传递给 MainWindow,您必须在 MainWindow 内创建一个属性,例如名为 CommandArgs 的 List
属性,然后在创建 MainWindow 对象后循环 Args 列表并添加其内容到 CommandArgs 列表