- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 C# 新手,创建了一个运行良好的简单应用程序,但我想使用模式 MVVM 学习 C#。所以我正在尝试将我的应用程序迁移到 MVVM,但我感到很困惑
1) 打开后,应用程序会扫描一个文件夹并索引格式中的所有文件“[number] [name]” - 工作正常!
2) 我有一个只有一个文本框的窗口。用户键入一个数字并按 ENTER。此时我有一个 CatalogViewModel
,它是一个 File
集合,应该选择由 textBox 中的数字指定的文件并打开它。
问题 1: 在 MVVM 中,我无法将数据从我的 View Main
传递到我的 ViewModel CatalogViewModel
(我不确定如果我做对了)
问题 2: 我无法处理 ENTER 键并触发 CatalogViewModel
我对 MVVM 有点困惑,无法继续。我知道这很简单。请问如何解决这 2 个问题(请详细说明,我是 C# 及其所有概念的初学者)
更新 1:
尝试了 janonimus 对问题 1 的解决方案,但数据绑定(bind)只是一种方式。VM 的值转到 VIEW,但 VIEW 上的更改不会转到 VM。我用这种方式实现了 INotifyPropertyChanged
using Prism.Mvvm;
...
public class CatalogViewModel: BindableBase
{
private string selectedValue = "100";
public string SelectedValue
{
get { return selectedValue; }
set { SetProperty(ref selectedValue, value); }
}
但是数据绑定(bind)就在路上XAML
<TextBox x:Name="tbSelectedValue" Text="{Binding SelectedValue, Mode=TwoWay}"
更新 2
我找到了问题 1 的解决方案。 janonimus 提供的代码仅以一种方式工作,因为 TextBox.Text 的默认行为是在失去焦点时更新,但在我的情况下,它永远不会失去焦点 see this post
下面的代码解决了问题1:
Text="{Binding Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
问题 2 可以通过 Pedro Silva 的回答解决
if (e.Key == Key.Enter && tbSelectedValue.Text != String.Empty)
{
vm.OpenSelectedFile();
tbSelectedValue.Text = String.Empty;
}
但我想使用更复杂的方式实现它,使用 ICommand
。按照 janonimus 发送的建议,我创建了 BaseCommand 类 Exactly like this但是当我调用函数 OpenSelectedFile
private BaseCommand<CatalogViewModel> _selectFileCommand;
public ICommand SelectFileCommand
{
get
{
if (_selectFileCommand == null)
{
_selectFileCommand = new BaseCommand<CatalogViewModel>(OpenSelectedFile, true);
}
return _selectFileCommand;
}
}
public void OpenSelectedFile()
{
try
{
OpenFileByNumber(Int32.Parse(SelectedValue));
}
catch (Exception e)
{
MessageBox.Show("Número inválido: \'" + SelectedValue + "\"",
"ERRO", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
主.xaml.cs
namespace SLMT.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class Main : Window
{
public Main()
{
InitializeComponent();
DataContext = new CatalogViewModel();
chosenNumber.Focus();
}
// Permite inserir somente números
private void ChosenNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^ 0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
{
//catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
//catalog.OpenSelectedFile(); // Will become someting like this
chosenNumber.Text = String.Empty;
}
}
private int ConvertToInt(string value)
{
try
{
var str = value.Replace(" ", String.Empty);
return Int32.Parse(str);
}
catch (Exception exc)
{
MessageBox.Show("O número: \"" + chosenNumber.Text + "\" é inválido", "ERRO", MessageBoxButton.OK, MessageBoxImage.Error);
chosenNumber.Text = String.Empty;
return 0;
}
}
/// <summary>
/// Controll what wil lhappen if some KEYS are pressed on APP
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GMain_KeyUp(object sender, KeyEventArgs e)
{
switch (e.Key){
case Key.Escape:
Environment.Exit(0);
break;
case Key.F1:
//wListFiles = new ListFiles(catalog);
//wListFiles.ShowDialog();
//numeroEscolhido.Text = wListFiles.SelectFile();
//numeroEscolhido.SelectAll();
break;
}
}
}
}
ps: 注释行,我是从没有MVVM的版本导入的
主.xaml
<Window x:Name="wMain" x:Class="SLMT.Views.Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SLMT.Views"
mc:Ignorable="d"
Title="Ministério Tons" Height="364" Width="700" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
<Grid x:Name="gMain" KeyUp="GMain_KeyUp">
<Image x:Name="imgBackground" HorizontalAlignment="Left" Height="364" VerticalAlignment="Top" Width="700" Source="/SLMT;component/Resources/img/background2.jpg" Opacity="100"/>
<TextBox x:Name="chosenNumber" HorizontalAlignment="Center" Height="34" Margin="500,294,56,36" TextWrapping="Wrap" VerticalAlignment="Center" Width="144" BorderBrush="{x:Null}" Background="{x:Null}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" UndoLimit="50" ForceCursor="True" PreviewTextInput="ChosenNumber_PreviewTextInput" KeyUp="ChosenNumber_KeyUp" BorderThickness="0" FontSize="20" Opacity="0.6" FontWeight="Bold"/>
</Grid>
</Window>
以及 CatalogViewModel.cs 的相关部分
namespace SLMT.ViewModel
{
public class CatalogViewModel: ObservableCollection <File>
{
private int selectedNumber;
/// <summary>
/// Contain the selected number in the View
/// </summary>
public int SelectedNumber
{
get { return selectedNumber; }
set { selectedNumber = value; }
}
// REMOVED CODE TO SCAN AND INDEX THE FILES
public CatalogViewModel() : base()
{
ScanFiles();
ValidateAndAddFiles();
ShowAlerts();
}
public void OpenSelectedFile()
{
OpenFileByNumber(SelectedNumber);
}
/// <summary>
/// Get the file from catalog identified my the number
/// </summary>
/// <param name="number"></param>
/// <returns>File|null</returns>
private File GetFileByNumber(int number)
{
foreach (var file in this)
{
if (file.number == number){
return file;
}
}
return null;
}
private void OpenFileByNumber(int number)
{
var file = GetFileByNumber(number);
if (file == null)
{
MessageBox.Show("Nenhum arquivo encontrado com o número: \'" + number +"\"",
"ARQUIVO NÃO ENCONTRADO", MessageBoxButton.OK, MessageBoxImage.Warning);
} else
{
file.Open();
}
}
}
}
最佳答案
尝试以下操作以访问您在构造函数中创建的 View 模型。
CatalogViewModel vm = new CatalogViewModel();
public Main()
{
InitializeComponent();
DataContext = vm;
chosenNumber.Focus();
}
然后在您的 key 处理程序中,您可以这样做:
private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
{
//catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
//catalog.OpenSelectedFile(); // Will become someting like this
vm.OpenSelectedFile();
chosenNumber.Text = String.Empty;
}
}
更新:使用 ICommand
使用您从 here 指向的 BaseCommand 类.我将以下代码添加到 CatalogViewModel 并使其正常工作。您将 BaseCommand 中的类型作为 View 模型,但这应该是命令参数的类型(基于该帖子中的示例)。
private BaseCommand<object> _selectFileCommand;
public ICommand SelectFileCommand
{
get
{
if (_selectFileCommand == null)
{
_selectFileCommand = new BaseCommand<object>((commandParam) => OpenSelectedFile(commandParam),
(commandParam) => CanOpenSelectedFile(commandParam));
}
return _selectFileCommand;
}
}
public void OpenSelectedFile(object commandParam = null)
{
Debug.WriteLine("CatalogViewModel.OpenSelectedFile was called.");
Debug.WriteLine("SelectedValue = " + this.SelectedValue);
}
public bool CanOpenSelectedFile(object commandParam = null)
{
return true;
}
进入 OpenSelectedFile 方法后,您应该能够将它连接到您想要的功能。
关于c# - 了解 MVVM - 如何绑定(bind)数据 View ↔ ViewModel + catch Key pressed on view and start function in viewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43127642/
我不知道该怎么做... function f1() { var x = 10; function f2(fx) { var x; x = 6;
早期绑定(bind)和后期绑定(bind)有什么区别? 最佳答案 简短的回答是,早期(或静态)绑定(bind)是指编译时绑定(bind),后期(或动态)绑定(bind)是指运行时绑定(bind)(例如
如何在 SwiftUI View 上使用 Binding(get: { }, set: { }) 自定义绑定(bind)与 @Binding 属性。我已成功使用此自定义绑定(bind)与 @State
我经常发现自己遇到问题,即控件的两个(相关)值被更新,并且两者都会触发昂贵的操作,或者控件可能会暂时处于不一致的状态。 例如,考虑一个数据绑定(bind),其中两个值 (x,y) 相互减去,最终结果用
我想通过我的 ViewModel 控制我的一个窗口的高度和宽度。 这看起来很简单。 但没有。它不起作用。 它检查 ViewModel 的 Width但不是 Height . 奇怪的是,如果我切换 W
UI5中一次性绑定(bind)和单向绑定(bind)有什么区别? 是否有任何用户特定的用例我会使用它们? 我无法从文档中获得太多信息。 最佳答案 单程 它的作用:单向数据流。模型数据的变化(例如通过
(define make (lambda (x) (lambda (y) (cons x (list y))))) (let ((x 7) (p (make 4))) (cons
尽管我或多或少地了解什么是语言绑定(bind),但我很难理解它们是如何工作的。 例如,谁能解释一下如何为 WinAPI 制作 Java 绑定(bind)? 最佳答案 如果您搜索 Foreign Fun
谁能解释为什么我可以重新绑定(bind)列表但不能+? (binding [list vector] (list 1 3)) (binding [list +] (list 1 3)) (bi
我真的很喜欢 Caliburn 和命名约定绑定(bind),我很惊讶 可见性与“CanNAME”约定用于保护 Action 的方式不同。 据我所知, BooleanToVisibilityConver
我了解动态绑定(bind)的实现方式以及静态绑定(bind)和动态绑定(bind)之间的区别,但我只是无法理解动态绑定(bind)的定义。基本上它是一种运行时绑定(bind)类型。 最佳答案 基本上,
http://jsfiddle.net/3NRsd/ var foo = $("div").bind("click", function() { $("div").animate({"hei
这个问题我快疯了...我有一个用户控件,它有一个用于插入操作的 FormView 和一个用于所有其他操作的 GridView。 在这两个控件中,我都有一个 DropDownList,如下所示: '
我有一个绑定(bind)到 ListBox 的地址的 ObservableCollection。然后在 ItemTemplate 中,我使用 {Binding .} 绑定(bind)到当前地址记录。这
如果我有以下简单的 js/knockout 代码: .js( View 模型): var image = ko.observable('http://placehold.it/300x150'); 看
我正在 aurelia 上开发一个自定义属性,让用户在输入文本区域时从列表中进行选择。例如,用法将是这样的: 正如您可能注意到的,auto-complete是属性。现在,当我想显示提示时,我想在自定
我正在使用 EventEmitter2作为我的应用程序内部的消息总线。现在我需要绑定(bind)和取消绑定(bind)一些事件处理程序。因为我也希望他们bind将它们添加到给定的上下文中,我最终得到以
我有以下函数调用: $(".selector").on("click", callback.bind(this, param1, param2)); 在我的回调函数中,我想使用绑定(bind)的 th
我目前正在试验新的编译绑定(bind),并且(再次)达到了我在拼图中遗漏了一个小问题:为什么我必须调用 Bindings.Update?直到现在,我还认为实现 INotifyPropertyChang
我正在阅读一本关于编写 JavaScript 框架的书,并找到了这段代码。但是我不明白它是如何工作的,尤其是 bind.bind 的用法?有人知道吗? var bind = Function.prot
我是一名优秀的程序员,十分优秀!