2014-03-27 41 views
0

如何從其他項目更改wpf用戶內容。例如,我有兩個用戶控制項目。當第二個wpf用戶項目中的時鐘打勾時,我想在第一個用戶控制項目中更改文本框。可能嗎 ?如何從其他項目更改wpf用戶內容

第一個項目

<UserControl x:Class="StatusBar.StatusBarWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="30" d:DesignWidth="800"> 
<Grid> 
    <StatusBar VerticalAlignment="Bottom" Grid.Column="0" Background="{x:Null}"> 
     <StatusBarItem HorizontalAlignment="Right"> 
      <TextBox x:Name="TxtClock" IsReadOnly="True" Background="{x:Null}" BorderThickness="0" Foreground="Black" x:FieldModifier="public" Text="i want change" /> 
     </StatusBarItem> 
    </StatusBar> 
</Grid> 

第二個項目

DispatcherTimer clock = new DispatcherTimer(); 
TxtSaat.Text = string.Format("{0:HH:mm:ss}", DateTime.Now); 
clock.Tick += new EventHandler(Clock_Tick); 
clock.Interval = new TimeSpan(0, 0, 1); 
clock.Start(); 
private void Clock_Tick(object sender, EventArgs e) 
     { 
      TxtClock.Text = string.Format("{0:HH:mm:ss}", DateTime.Now); 
     } 

回答

0

首先,你需要獲得用戶控件的實例莫名其妙。鑑於這種情況,您可以使用此:

userControlInstance.TxtClock.Text = String.Format("{0:HH:mm:ss}", DateTime.Now); 

或者你可以給用戶控件的屬性:

private DateTime _displayTime; 
public DateTime DisplayTime 
{ 
    get { return _displayTime; } 
    set { 
     _displayTime = value; 
     TxtClock.Text = String.Format("{0:HH:mm:ss}", _displayTime); 
    } 
} 

和外界通話

userControlInstance.DisplayTime = DateTime.Now; 

重要的部分是:您需要訪問用戶控件的實例。

+0

我做到了。但用戶控制不更新。 –

+0

讓我猜。你在窗口中有一個用戶控件,並且你使用'... = new MyUserControl();'創建了一個實例,你運行更新並且現在顯示沒有更新? –

+0

是的。你是對的。 –

0

您面對的問題部分是由於UserControl中的程序邏輯引起的。這往往會讓事情變得更棘手。理想情況下,只有特定於視圖的東西應該放在UserControl中,理想情況下,它只是xaml,沒有代碼。

我會建議做一個非視圖類,其中所有的邏輯可以保存。例如:

class ClockViewModel : INotifyPropertyChanged 
{ 
    public ClockViewModel() 
    { 
     ... 
     clock.Tick += new EventHandler(Clock_Tick); 
    } 

    private void Clock_Tick(object sender, EventArgs e) 
    { 
     Tick = string.Format("{0:HH:mm:ss}", DateTime.Now); 
    } 

    string _tick=""; 
    public string Tick 
    { 
     get 
     { 
      return _tick; 
     } 
     set 
     { 
      _tick = value; 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs("Tick")); 
     } 
    } 
} 

然後你的意見可以綁定到類的同一個實例(只注入相同的情況下到他們的構造函數或屬性)。然後在你的xaml中,你可以這樣做:

<TextBox Text="{Binding Tick}"/> 

而你的文本框會自動更新每個勾號。這樣你的邏輯就不需要了解TextBox或一般的視圖。問題就變成了如何在不同項目中的代碼之間共享同一個ClockViewModel類的實例?爲此,您可以通過構造函數或屬性設置器注入。

相關問題