- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近在我的代码中实现了一个解决方案,允许我在我的 View 模型中绑定(bind)到我的命令。这是我使用的方法的链接:https://code.msdn.microsoft.com/Event-to-Command-24d903c8 .我在链接中使用了第二种方法。您可以出于所有意图和目的假设我的代码与此代码非常相似。这工作得很好。但是,我还需要为此双击绑定(bind)一个命令参数。我该如何设置?
这是我的项目的一些背景。这个项目背后的一些设置可能看起来很奇怪,但必须以这种方式完成,因为我不会在这里讨论很多细节。首先要注意的是,这种绑定(bind)设置发生在多值转换器内部。这是我生成新元素的代码:
DataTemplate dt = new DataTemplate();
dt.DataType = typeof(Button);
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
btn.SetValue(Attached.DoubleClickCommandProperty, ((CardManagementViewModel)values[1]).ChangeImageCommand);
dt.VisualTree = btn;
private RelayCommand _ChangeImageCommand;
public ICommand ChangeImageCommand
{
get
{
if (_ChangeImageCommand == null)
{
_ChangeImageCommand = new RelayCommand(
param => this.ChangeImage(param)
);
}
return _ChangeImageCommand;
}
}
private void ChangeImage(object cardParam)
{
}
private ObservableCollection<string> _MyList;
public ObservableCollection<string> MyList { get { return _MyList; } set { if (_MyList != value) { _MyList = value; RaisePropertyChanged("MyList"); } } }
public ViewModel()
{
MyList = new ObservableCollection<string>();
MyList.Add("str1");
MyList.Add("str2");
MyList.Add("str3");
}
<ContentControl>
<ContentControl.Content>
<MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
<Binding Path="MyList"/>
<Binding />
</MultiBinding>
</ContentControl.Content>
</ContentControl>
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
ListBox lb = new ListBox();
lb.ItemsSource = (ObservableCollection<string>)values[0];
DataTemplate dt = new DataTemplate();
dt.DataType = typeof(Button);
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
btn.SetValue(Button.WidthProperty, 100D);
btn.SetValue(Button.HeightProperty, 50D);
btn.SetBinding(Button.ContentProperty, new Binding());
dt.VisualTree = btn;
lb.ItemTemplate = dt;
return lb;
}
private RelayCommand _MyCommand;
public ICommand MyCommand
{
get
{
if (_MyCommand == null)
{
_MyCommand = new RelayCommand(
param => this.MyMethod(param)
);
}
return _MyCommand;
}
}
private void MyMethod(object myParam)
{
MyList.Add(myParam.ToString());
}
public class Attached
{
static ICommand command;
public static ICommand GetDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DoubleClickCommandProperty);
}
public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DoubleClickCommandProperty, value);
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Attached), new UIPropertyMetadata(null, CommandChanged));
static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var fe = obj as FrameworkElement;
command = e.NewValue as ICommand;
fe.AddHandler(Button.MouseDoubleClickEvent, new RoutedEventHandler(ExecuteCommand));
}
static void ExecuteCommand(object sender, RoutedEventArgs e)
{
var ele = sender as Button;
command.Execute(null);
}
}
btn.SetValue(Attached.DoubleClickCommandProperty, ((ViewModel)values[1]).MyCommand);
using System.Collections.ObjectModel;
using System.Windows.Input;
using WpfApplication2.Helpers;
namespace WpfApplication2
{
public class ViewModel : ObservableObject
{
private ObservableCollection<string> _MyList;
private RelayCommand _MyCommand;
public ObservableCollection<string> MyList { get { return _MyList; } set { if (_MyList != value) { _MyList = value; RaisePropertyChanged("MyList"); } } }
public ViewModel()
{
MyList = new ObservableCollection<string>();
MyList.Add("str1");
MyList.Add("str2");
MyList.Add("str3");
}
public ICommand MyCommand
{
get
{
if (_MyCommand == null)
{
_MyCommand = new RelayCommand(
param => this.MyMethod(param)
);
}
return _MyCommand;
}
}
private void MyMethod(object myParam)
{
MyList.Add(myParam.ToString());
}
}
}
<Window x:Class="WpfApplication2.MainWindow"
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:helpers="clr-namespace:WpfApplication2.Helpers"
xmlns:Converters="clr-namespace:WpfApplication2.Helpers.Converters"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Window.Resources>
<Converters:MyConverter x:Key="MyConverter"/>
</Window.Resources>
<ContentControl>
<ContentControl.Content>
<MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
<Binding Path="MyList"/>
<Binding />
</MultiBinding>
</ContentControl.Content>
</ContentControl>
</Window>
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace WpfApplication2.Helpers.Converters
{
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
ListBox lb = new ListBox();
lb.ItemsSource = (ObservableCollection<string>)values[0];
DataTemplate dt = new DataTemplate();
dt.DataType = typeof(Button);
FrameworkElementFactory btn = new FrameworkElementFactory(typeof(Button));
btn.SetValue(Button.WidthProperty, 100D);
btn.SetValue(Button.HeightProperty, 50D);
btn.SetBinding(Button.ContentProperty, new Binding());
btn.SetValue(Attached.DoubleClickCommandProperty, ((ViewModel)values[1]).MyCommand);
// Somehow create binding so that I can pass the selected item of the listbox to the
// above command when the button is double clicked.
dt.VisualTree = btn;
lb.ItemTemplate = dt;
return lb;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication2.Helpers
{
public class Attached
{
static ICommand command;
public static ICommand GetDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DoubleClickCommandProperty);
}
public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DoubleClickCommandProperty, value);
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Attached), new UIPropertyMetadata(null, CommandChanged));
static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var fe = obj as FrameworkElement;
command = e.NewValue as ICommand;
fe.AddHandler(Button.MouseDoubleClickEvent, new RoutedEventHandler(ExecuteCommand));
}
static void ExecuteCommand(object sender, RoutedEventArgs e)
{
var ele = sender as Button;
command.Execute(null);
}
}
}
using System;
using System.ComponentModel;
using System.Diagnostics;
namespace WpfApplication2.Helpers
{
public class ObservableObject : INotifyPropertyChanged
{
#region Debugging Aides
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public virtual void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
#endregion // Debugging Aides
#region INotifyPropertyChanged Members
/// <summary>
/// Raises the PropertyChange event for the property specified
/// </summary>
/// <param name="propertyName">Property name to update. Is case-sensitive.</param>
public virtual void RaisePropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
OnPropertyChanged(propertyName);
}
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion // INotifyPropertyChanged Members
}
}
using System;
using System.Diagnostics;
using System.Windows.Input;
namespace WpfApplication2.Helpers
{
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
#endregion // ICommand Members
}
}
最佳答案
您发布的代码实际上不是 最小 或 完整例子。至少,它缺少 CardManagementViewModel
类型,当然该示例似乎是基于原始代码的,并没有尝试将其简化为最小示例。
因此,我没有花太多时间查看所有代码,更不用说我费心编译和运行它了。但是,原始编辑中缺少的主要内容是附加属性的实现。所以有了这个,我建议你改变你的Attached
类,所以它看起来像这样:
public class Attached
{
public static ICommand GetDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DoubleClickCommandProperty);
}
public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DoubleClickCommandProperty, value);
}
public static object GetDoubleClickCommandParameter(DependencyObject obj)
{
return obj.GetValue(DoubleClickCommandParameterProperty);
}
public static void SetDoubleClickCommandParameter(DependencyObject obj, object value)
{
obj.SetValue(DoubleClickCommandParameterProperty, value);
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Attached), new UIPropertyMetadata(null, CommandChanged));
public static readonly DependencyProperty DoubleClickCommandParameterProperty =
DependencyProperty.RegisterAttached("DoubleClickCommandParameter", typeof(object), typeof(Attached));
static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var fe = obj as FrameworkElement;
if (e.OldValue == null && e.NewValue != null)
{
fe.AddHandler(Button.MouseDoubleClickEvent, ExecuteCommand);
}
else if (e.OldValue != null && e.NewValue == null)
{
fe.RemoveHandler(Button.MouseDoubleClickEvent, ExecuteCommand);
}
}
static void ExecuteCommand(object sender, RoutedEventArgs e)
{
var ele = sender as Button;
ICommand command = GetDoubleClickCommand(ele);
object parameter = GetDoubleClickCommandParameter(ele);
command.Execute(parameter);
}
}
Attached.DoubleClickCommandParameter
附属属性(property)。这将允许您在设置命令本身的同时设置命令参数。
ICommand
在 static
字段,因为您的实现有它。按照你的代码的方式,你一次只能有一个命令。如果您尝试在多个元素上设置附加属性,并且使用了多个 ICommand
值,你仍然只能得到最近设置的 ICommand
.使用我的更改,您将始终获得您设置的命令。 Attached.SetDoubleClickCommand(btn, ((CardManagementViewModel)values[1]).ChangeImageCommand);
Attached.SetDoubleClickCommandParameter(btn, ((CardManagementViewModel)values[1]).ChangeImageCommandParameter);
ChangeImageCommandParameter
存储要发送的参数的属性。您当然可以将属性值设置为您想要的任何值,例如引用所选项目或其他内容的值。
Attached
类的属性 setter 方法,这是对 WPF 中附加属性抽象的更恰当的使用。当然,在大多数实现中,它与调用
SetValue()
完全相同。方法,但最好通过附加属性的方法,以防它们以某种方式自定义行为。
CommandProperty
值)。
关于c# - 在传递命令参数时绑定(bind)到代码中的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39965583/
我不知道该怎么做... 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
我是一名优秀的程序员,十分优秀!