【发布时间】:2017-11-17 13:35:47
【问题描述】:
我正在尝试将一些东西绑定到我的 wpf,它由 2 个窗口组成。我能够将数据绑定到第一个窗口,但无法真正考虑如何在第二个窗口中完成:
主窗口代码:
public partial class MainWindow : Window
{
private string repeatNumber;
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
List<Images> animals = new List<Images>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(new Images() { Source = repeatNumber, Number = i });
}
else if ((i % 9) == 0)
{
animals.Add(new Images() { Source = repeatNumber, Number = i });
}
else
{
animals.Add(new Images() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
}
ItemsControl1.ItemsSource = animals;
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("test");
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
Window1 window1 = new Window1();
window1.Show();
}
}
}
class Images
{
public int Number { get; set; }
public string Source { get; set; }
}
主窗口 xaml:
<Grid>
<ListBox x:Name="ItemsControl1">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5">
</UniformGrid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="3" Width="Auto" Height="Auto">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"/>
<Image Source="{Binding Source}" Margin="0,0,5,0"/>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid>
<Button x:Name="btn1" Click="btn1_Click" Height="20" VerticalAlignment="Bottom" Margin="127,0,316,0" Content="Instruction"></Button>
<Button x:Name="btn2" Click="btn2_Click" Height="20" VerticalAlignment="Bottom" Margin="300,0,109,0" Content="Results" Width="74"> </Button>
</Grid>
</Grid>
Window2 代码现在只是:
public class Window2 : Window
{
//should return the value of repeatNumber
}
xaml for windows2 我现在只是:
<Grid>
</Grid>
我试图从 MainWindow repeatNumber 中获取值。我怎样才能做到这一点?
【问题讨论】:
-
您可以将绑定到另一个窗口的变量作为参数传递给它的构造函数。或者您可以将它们定义为 window2 代码隐藏下的公共属性。更好的方法可能是定义一个通用的视图模型并使用构造函数共享它。
-
你真的应该看看这个msdn.microsoft.com/en-us/magazine/dd419663.aspx。使用 MVVM,您可以将窗口的逻辑放入一个名为 viewmodel 的类中。然后,您可以使用这个类将可用数据提供给您想要的任何窗口或用户控件