我有以下代码:
窗口1:
<NVD3Chart
id="barChart"
type="multiBarChart"
width={document.body.clientWidth-(document.body.clientWidth*0.13)}
height={400}
showLabel={false}
stacked={true}
showControls={true}
showLegend={true}
datum={this.state.activityOptions}
color={['#3fceb1','#fff480']}
x="label"
y="values"
reduceXTicks={false}
tickFormat={d3.format('d')}/>
第二窗口:
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondWindow sndW = new SecondWindow(btnFirstWindow);
sndW.Show();
}
<Grid>
<Button Name="btnFirstWindow" Content="Button" HorizontalAlignment="Left" Margin="317,166,0,0" VerticalAlignment="Top" Width="148" Height="70" Click="Button_Click"/>
</Grid>
如果我按下window1中的按钮,它应该从window2中的lblShowUser更改内容。从here得到了这个例子。但它不会起作用.. 两个窗口将打开,但内容不会改变。如果我将标签中的内容设置为&#34; test&#34;,它将无法更改为正确的时间,例如&#34;点击第一个窗口按钮:...&#34;
答案 0 :(得分:0)
移动此代码 firstWindowButton.Click + = firstWindowButton_Click;
到SecondWindow构造函数。所以看起来应该是这样的:
public SecondWindow(Button firstWindowButton) {
this.firstWindowButton = firstWindowButton;
firstWindowButton.Click += firstWindowButton_Click;
InitializeComponent();
}
答案 1 :(得分:0)
另一种方法是将两个窗口绑定到同一个ViewModel
,并在 App.xaml 中将ViewModel定义为s StaticResource
:
添加Command
类和SharedViewModel
类并定义所需的属性/命令:
public class Command : ICommand
{
private readonly Action _action;
public Command(Action action)
{
_action = action;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_action();
}
}
public class SharedViewModel : INotifyPropertyChanged
{
private string _labelText;
public string LabelText
{
get { return _labelText; }
set
{
_labelText = value;
OnPropertyChanged();
}
}
private ICommand _buttonClickCommand;
public ICommand ButtonClickCommand => _buttonClickCommand ?? (_buttonClickCommand = new Command(ButtonClickAction));
public void ButtonClickAction()
{
LabelText = "Updated Text";
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在 App.xaml 中将SharedViewModel
实例定义为StaticResource
:
<Application.Resources>
<ResourceDictionary>
<local:SharedViewModel x:Key="SharedViewModel"/>
</ResourceDictionary>
窗口1:
Title="MainWindow" Height="450" Width="800" DataContext="{StaticResource SharedViewModel}">
<Grid>
<Button Name="BtnFirstWindow" Content="Button" HorizontalAlignment="Left" Margin="317,166,0,0" VerticalAlignment="Top" Width="148" Height="70" Command="{Binding ButtonClickCommand}"/>
</Grid>
窗口2
Title="Window2" Height="450" Width="800" DataContext="{StaticResource SharedViewModel}">
<Grid>
<Label Name="lblShowUser" Content="{Binding LabelText}" HorizontalAlignment="Left" Margin="275,175,0,0" VerticalAlignment="Top" Height="92" Width="205"/>
</Grid>