我正在尝试在 c# 中进行从Winforms
to的转换。WPF
我在WVVM
and有点挣扎data binding
。我承认我没有完全掌握一切如何协同工作,但我认为我需要更多的练习。
我在 codeproject 上使用了这篇文章来帮助我了解如何将本地通讯簿应用程序从 WinForms 转换为 WPF。
虽然我可以让数据绑定与 int 和 string 一起正常工作,但我正在努力使用 ComboBox。数据存储在 xml 文件中,并以字符串和整数的形式存储在联系人类中。从列表框中选择位置时,组合框应自动更新。我将这一切都用于允许用户自定义信息的属性。此特定设置需要是预设值的下拉菜单。
如何转换字符串并通过数据绑定将 SelectedIndex[] 属性传递给组合框?
我省略了一些在字符串填充中用于文本框的额外工作代码来清理它。
XAML
<Window
<Window.DataContext>
<viewmodels:mainviewModel x:Name="viewModel1"/>
</Window.DataContext>
<Grid Background="#FF8B8686">
<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="174" Margin="44,77,0,0" VerticalAlignment="Top" Width="164" ItemsSource="{Binding Contacts}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedContact}" SelectionChanged="listBox_SelectionChanged" />
<TextBox x:Name="textBoxName" HorizontalAlignment="Left" Height="23" Margin="244,77,0,0" TextWrapping="Wrap" Text="{Binding SelectedContact.Name}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textBoxAddress" HorizontalAlignment="Left" Height="23" Margin="244,120,0,0" TextWrapping="Wrap" Text="{Binding SelectedContact.Address}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textBoxBandwidth" HorizontalAlignment="Left" Height="23" Margin="244,198,0,0" TextWrapping="Wrap" Text="{Binding SelectedContact.Bandwidth}" VerticalAlignment="Top" Width="120" DataContext="{Binding Mode=OneWay}"/>
<Button x:Name="button1" Content="Write Data" HorizontalAlignment="Left" Margin="194,271,0,0" VerticalAlignment="Top" Width="75" Click="button1_Click"/>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="267,229,0,0" VerticalAlignment="Top" Width="120" SelectedItem="{Binding SelectedContact.Combo}">
<ComboBoxItem Content="1" />
<ComboBoxItem Content="2" />
<ComboBoxItem Content="3" />
<ComboBoxItem Content="4" />
</ComboBox>
</Grid>
</Window>
联系人.cs
public class Contact : ViewModelEntity
{
public Contact()
{
}
protected int combo;
public int Combo
{
get { return combo; }
set
{
if (combo != value)
{
switch (value)
{
case 1:
combo = ComboBox.SelectedIndex[0];
break;
case 2:
combo = ComboBox.SelectedIndex[1];
break;
case 3:
combo = ComboBox.SelectedIndex[2];
break;
case 4:
combo = ComboBox.SelectedIndex[3];
break;
default:
combo = ComboBox.SelectedIndex[0];
break;
}
// combo = value;
NotifyPropertyChanged("Combo");
}
}
}
主视图模型.cs
using System.Collections.ObjectModel;
namespace WpfApplication1.viewmodels
{
public class mainviewModel:ViewModelEntity
{
public mainviewModel()
{ }
protected Contact selectedContact = null;
protected ObservableCollection<Contact> contacts = new ObservableCollection<Contact>();
public ObservableCollection<Contact> Contacts
{
get { return contacts; }
set { contacts = value; }
}
public Contact SelectedContact
{
get { return selectedContact; }
set {
if (selectedContact != value)
{
selectedContact = value;
NotifyPropertyChanged("SelectedContact");
}
}
}
}
}