【问题标题】:combobox binding MVVM C#组合框绑定 MVVM C#
【发布时间】:2018-06-12 00:17:31
【问题描述】:

我错过了一些东西,但我不知道是什么:(

我已将 IEnumerable 集合绑定到组合框。我想将其选定的值用作关机命令的参数,但是当我按下开始按钮时,它不会加载选定的值。

我遵循了一些教程来了解 MVVM,但仍然缺少一些东西,但我不知道是什么。

这是 MainWindow.xaml :

<grid>
    <StackPanel>
        <!--Title label-->
        <TextBlock Text="Wyłącz komputer za:" Margin="5"/>

        <!-- Blocks used to set hours and minutes-->
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Godziny:" Margin="5"/>
            <ComboBox x:Name="HoursCB" Margin="5" Width="40" ItemsSource="{Binding myHours}" SelectedValue="{Binding selectedHours, UpdateSourceTrigger=PropertyChanged}" />
            <TextBlock Text="Minuty:" Margin="5" />
            <ComboBox x:Name="MinutesCB" Margin="5" Width="40" ItemsSource="{Binding myMinutes}" SelectedValue="{Binding selectedMinutes, UpdateSourceTrigger=PropertyChanged}" />
        </StackPanel >

        <!-- Timer -->
        <StackPanel Orientation="Horizontal">
            <Label x:Name="HHLabel" Content="{Binding selectedHours}" FontSize="30" HorizontalAlignment="Center" Width="45"/>
            <Label x:Name="Colon1" Content=":" FontSize="30" HorizontalAlignment="Center" Width="25"/>
            <Label x:Name="MMLabel" Content="{Binding selectedMinutes}" FontSize="30" HorizontalAlignment="Center" Width="45"/>
            <Label x:Name="Colon2" Content=":" FontSize="30" HorizontalAlignment="Center" Width="25"/>
            <Label x:Name="SSLabel" Content="00" FontSize="30" HorizontalAlignment="Right" Width="45"/>
        </StackPanel>

        <!-- Start Button -->
        <Button Content="uruchom odliczanie" Margin="5" Command="{Binding StartCommand}" />

        <!-- Stop Button-->
        <Button Content="Zatrzymaj odliczanie" Margin="5" Command="{Binding StopCommand}"/>
    </StackPanel>
</grid>

这是视图模型:

class MainWindowViewModel : INotifyPropertyChanged
{
    public MainWindowViewModel()
    {
        StartCommand = new AddNameCommand(this);
    }

    class AddNameCommand : ICommand
    {
        MainWindowViewModel parent;

        public AddNameCommand(MainWindowViewModel parent)
        {
            this.parent = parent;
            parent.PropertyChanged += delegate { CanExecuteChanged?.Invoke(this, EventArgs.Empty); };
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        { return true; }

        public void Execute(object parameter)
        {
            int num = parent.SelectedHours * 3600 + parent.SelectedMinutes * 60;
            MessageBox.Show($"Shutting down the computer in {num} !");
            //Process.Start("shutdown", string.Format("/s /t {0}", num));
        }
    }

    public ICommand StartCommand { get; private set; }


    /// <summary>
    /// Combobox Items.
    /// </summary>
    //public IEnumerable<int> myHours = Enumerable.Range(0, 23);
    //public IEnumerable<int> myMinutes = Enumerable.Range(1, 59);
    public ObservableCollection<int> myHours { get; set; } = new ObservableCollection<int>(Enumerable.Range(0, 23));
    public ObservableCollection<int> myMinutes { get; set; } = new ObservableCollection<int>(Enumerable.Range(1, 59));


    /// <summary>
    /// Selected time properties.
    /// </summary>
    public int SelectedMinutes
    {
        get { return mSelectedMinutes; }
        set
        {
            if (value == mSelectedMinutes)
                return;
            mSelectedMinutes = value;
            OnPropertyChanged();
        }
    }
    int mSelectedMinutes;

    public int SelectedHours
    {
        get { return mSelectedHours; }
        set
        {
            if (value == mSelectedHours)
                return;
            mSelectedHours = value;
            OnPropertyChanged();
        }
    }
    int mSelectedHours;

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName]string propertyName = null)
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
}

【问题讨论】:

  • 组合框是否正确填充?仅在SelectedValue 中遇到问题
  • 是的。出于某种原因,有 22 小时而不是 23 小时,但休息很好。

标签: c# wpf mvvm combobox binding


【解决方案1】:

您尚未将组合框的选定值绑定到视图模型中的正确属性。只需在 XAML 中将“selectedHours”更改为“SelectedHours”,将“selectedMinutes”更改为“SelectedMinutes”即可正确绑定。

【讨论】:

    【解决方案2】:

    您应该将xaml 更改为以下内容(注意区分大小写SelectedHours/Minutes):

        <!-- Blocks used to set hours and minutes-->
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Godziny:" Margin="5"/>
            <ComboBox x:Name="HoursCB" Margin="5" Width="40" ItemsSource="{Binding myHours}" SelectedValue="{Binding SelectedHours, UpdateSourceTrigger=PropertyChanged}" />
            <TextBlock Text="Minuty:" Margin="5" />
            <ComboBox x:Name="MinutesCB" Margin="5" Width="40" ItemsSource="{Binding myMinutes}" SelectedValue="{Binding SelectedMinutes, UpdateSourceTrigger=PropertyChanged}" />
        </StackPanel >
    

    通过打开Visual Studio 中的Output Window 并查找以下内容,可以轻松检测到绑定错误:

    System.Windows.Data Error: 40 : BindingExpression path error: 'selectedHours' property not found on 'object' ''MainWindowViewModel' (HashCode=46431654)'. BindingExpression:Path=selectedHours; DataItem='MainWindowViewModel' (HashCode=46431654); target element is 'ComboBox' (Name='HoursCB'); target property is 'SelectedValue' (type 'Object')
    

    【讨论】:

    • 哈哈哈!!!就是这样一个:)感谢有关此输出窗口的建议:)
    【解决方案3】:

    你的代码表现得像我加快了它。您的问题是 Enumerable.Range 函数。它以包含 0 开始,然后计数 23 次包含 0

    【讨论】:

    • 好吧,它解释了为什么我只有 22 小时在组合框中,但最大的问题不是 workingshutdown 命令
    • 我在您的代码中没有看到任何关机命令。只有开始和停止。您是指 AddName/Start 命令吗?
    • 启动按钮应该运行启动命令,它应该在执行方法中运行注释行,其值取自组合框但是当我运行此行时它会立即关闭计算机
    • 我用 MessageBox 模拟关机命令,但它显示“Shutting in 0”
    猜你喜欢
    • 2015-04-27
    • 2011-06-13
    • 2015-09-15
    • 1970-01-01
    • 2021-10-11
    • 2015-07-11
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多