2015-09-21 3 views
1

У меня есть приложение wpf, которое нужно вызывать с несколькими аргументами командной строки. Как показать их в ярлыках, которые я поместил в окно именно по этой причине? Я попытался реализовать привязку данных, но безуспешно, - переменная читается и назначается правильно, но по какой-то абсурдной причине не отображается на экране, на метке, которую я хочу. Вот код: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:

<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"/> 

Спасибо anticipately.

+1

Экземпляр MainWindow внутри вашего приложения. Метод OnStartUp не совпадает с StartupUri, указанным в App.xaml –

+0

См. Например. http://stackoverflow.com/a/25661138/1061668 –

+0

Чтобы передать свои аргументы в MainWindow, вы должны создать Свойство внутри MainWindow, например, свойство List с именем CommandArgs, а после создания цикла MainWindow Object Args список и добавить его содержимое в список CommandArgs –

ответ

2

Пример иллюстрирует, как отображать аргументы в метке.

Это точка входа приложения:

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    { 
     var argumentsInfo = BuildArgumentsInfo(e.Args); 
     var viewModel = new MainWindowViewModel(argumentsInfo); 
     var window = new MainWindow(viewModel); 
     window.Show(); 
    } 

    private string BuildArgumentsInfo(string[] args) 
    { 
     return args.Any() 
      ? args.Aggregate((arg1, arg2) => arg1 + " " + arg2) 
      : "No arguments"; 
    } 
} 

Это вид модели (контекст данных с точки зрения):

public interface IMainWindowViewModel 
{ 
    string Arguments { get; set; } 
} 

public class MainWindowViewModel : IMainWindowViewModel, INotifyPropertyChanged 
{ 
    private string _arguments; 

    public MainWindowViewModel(string argumentsInfo) 
    { 
     Arguments = argumentsInfo; 
    } 

    public string Arguments 
    { 
     get { return _arguments; } 
     set 
     { 
      _arguments = value; 
      RaisePropertyChanged("Arguments"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged = delegate {}; 

    private void RaisePropertyChanged(string propertyName) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

Это мнение (код сзади):

public partial class MainWindow : Window 
{ 
    public MainWindow(IMainWindowViewModel viewModel) 
    { 
     InitializeComponent(); 
     DataContext = viewModel; 
    } 
} 

И это метка в окне просмотра (XAML):

<Label Content ="{Binding Arguments}"></Label> 

Важно! Ваш должен удалить StartupUri="MainWindow.xaml из файла App.xaml, потому что MainWindow запускается из кода позади.

Смежные вопросы