[英]Bind WPF combobox itemssource to property in another .cs file
我正在嘗試將組合框綁定到我在另一個文件中定義的屬性。
在OptionsWindow.xaml
中的組合OptionsWindow.xaml
:
<ComboBox x:Name="InputDevicesComboBox"
VerticalAlignment="Top"
Text="Please Select Input Device"
ItemsSource="{Binding InputDeviceNames, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type SIPBandVoIPClient:MainWindow}}}"/>
該屬性,位於MainWindow.xaml.cs
:
private List<string> _inputDeviceNames;
public List<string> InputDeviceNames
{
get => _inputDeviceNames;
private set
{
_inputDeviceNames = value;
OnPropertyChanged("InputDeviceNames");
}
}
打開OptionsWindow時出現錯誤:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='SIPBandVoIPClient.MainWindow', AncestorLevel='1''. BindingExpression:Path=InputDeviceNames; DataItem=null; target element is 'ComboBox' (Name='InputDevicesComboBox'); target property is 'ItemsSource' (type 'IEnumerable')
我認識到有很多問題,但是我不太了解WPF綁定,似乎無法使它們正常工作...
我使用Visual Studio中的內置綁定創建了此綁定,因此我認為它可以工作。 經過一些搜索,我認為問題是該屬性位於其他文件中,或者它不屬於可視樹(?)。
我確實具有與MainWindow.xaml.cs中定義的屬性的綁定,並且已與MainWindow.xaml中的綁定良好地工作,因此,我認為這是由於位於不同的文件中。
謝謝您的幫助。
您可以創建一個視圖模型對象以在這兩個窗口之間交換數據,並將其傳遞給兩個窗口實例的DataContext。 然后,綁定屬性不需要任何相對源,只需在Path中設置包含列表的屬性名稱即可。 或者更好地看一下MVVM設計模式https://blogs.msdn.microsoft.com/msgulfcommunity/2013/03/13/understanding-the-basics-of-mvvm-design-pattern/
創建一個視圖模型類mainViewModel.cs:
class MainViewModel {
List<string> InputDeviceNames { get; private set; }
public MainViewModel() {
InputDeviceNames = new List<string>();
}
}
然后在MainWindow.xaml.cs類中使用它:
private MainViewModel _viewModel;
public MainWindow() {
_viewModel = new MainViewModel();
DataContext = _viewModel;
// anywhere in code you can use your _viewModel to exchange data
}
public OpenOptionsWindowCode() {
var options = new OptionsWindow();
options.DataContext = _viewModel;
options.Show();
}
在您的OptionsWindow.xaml中:
<ComboBox x:Name="InputDevicesComboBox"
VerticalAlignment="Top"
Text="Please Select Input Device"
ItemsSource="{Binding InputDeviceNames}"/>
如果在MainWindow.xaml的綁定中使用InputDeviceNames,請確保通知項目更改。 然后使用ObservableCollection<T>
代替List<T>
。 如果要擴展視圖模型以容納其他值,請在MainViewModel類上實現INotifyPropertyChanged
接口。
MVVM是用於UI開發的強大模式,因此,只需花些力氣就可以用更少的努力獲得更好的結果。
希望對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.