【发布时间】:2021-04-01 00:35:13
【问题描述】:
我有一个ComboBox,它会在SelectedItem 更改时写入配置文件。
我想使用SelectedIndex = -1 作为备用,以防SelectedItem 丢失。
我不希望SelectedIndex 在程序启动时触发并写入配置文件,所以我将事件处理程序放在C# Window_Loaded() 而不是XAML。
问题是Video_SelectedIndex = -1 没有选择任何内容,它使SelectedItem 留空。
主窗口
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cboPlugin_Video.SelectedIndex += VM.PluginsView.Video_SelectedIndex; // <-- Problem here
cboPlugin_Video.SelectionChanged += cboPlugin_Video_SelectionChanged;
我试图以另一种方式绑定它,但它在程序启动时触发。
cboPlugin_Video.DataContext = VM.PluginsView;
Binding Plugins_Video_SelectedIndexBinding = new Binding() { Source = VM.PluginsView, Path = new PropertyPath("Video_SelectedIndex"), Mode = BindingMode.TwoWay };
cboPlugin_Video.SetBinding(ComboBox.SelectedIndexProperty, Plugins_Video_SelectedIndexBinding);
XAML
<Window.DataContext>
<local:VM/>
</Window.DataContext>
<ComboBox x:Name="cboPlugin_Video"
DataContext="{Binding PluginsView}"
ItemsSource="{Binding Video_Items}"
SelectedItem="{Binding Video_SelectedItem}"
Margin="10,12,0,0"
VerticalAlignment="Top"
Height="22"
HorizontalAlignment="Left"
Width="140" />
视图模型
namespace ViewModel
{
public class PluginsViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop));
}
}
private int _Video_SelectedIndex { get; set; }
public int Video_SelectedIndex
{
get { return _Video_SelectedIndex; }
set
{
if (_Video_SelectedIndex == value)
{
return;
}
_Video_SelectedIndex = value;
OnPropertyChanged("Video_SelectedIndex");
}
}
选择项目/索引
// Plugin Found
if (test == "Example")
{
VM.PluginsView.Video_SelectedItem = "Example"; // Works
}
// Missing, Default to First Item
else
{
VM.PluginsView.Video_SelectedIndex = -1; // <-- Not working
}
选择更改事件
private void cboPlugin_Video_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Write to config file
// Works
}
【问题讨论】:
-
The problem is Video_SelectedIndex = -1 doesn't select anything, it leaves the SelectedItem blank. -
有错字吗?
cboPlugin_Video.SelectedIndex += VM.PluginsView.Video_SelectedIndex;- 不应该只是=而不是+=吗? -
@RandRandom 它看起来像
+=和-1而不是0是问题所在,但在将其更改为=后,它现在在启动时触发。 -
@RandRandom 我认为我不能正确地将它绑定到 ViewModel。我想我必须将
MainWindow传递给它并使用mainwindow.cboPlugin_Video.SelectedIndex = 0 -
您可以在
ContentRendered上注册SelectionChanged事件而不是加载docs.microsoft.com/en-us/dotnet/api/… - 这应该在所有绑定评估后发生