作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想比较和交换两个 ViewModel 公共(public)属性的值,最好使用如下方法:
void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
T temp;
if (lhs.CompareTo(rhs) > 0)
{
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
但是由于您不能通过 ref 传递属性,所以我不能在我的 ViewModel 中这样做。
private Int32 max;
public Int32 Max
{
get { return max; }
set
{
SwapIfGreater<Int32>(ref Min, ref Max);
max = value;
OnPropertyChanged("Max");
}
}
private Int32 min;
public Int32 Min
{
get { return min; }
set
{
SwapIfGreater<Int32>(ref Min, ref Max);
min = value;
OnPropertyChanged("Min");
}
}
否则...如果我只是尝试直接在 Min getter 或 setter 中使用“if compare”逻辑,当 Min 更改为大于 Max 的值时,我最终会得到 Min 等于 Max。
编辑:根据有关支持属性的建议,我已将方法修改为:
void SwapIfGreater<T>(ref T lhs, ref T rhs, String otherPropertyName) where T : System.IComparable<T>
{
T temp;
if (lhs.CompareTo(rhs) > 0)
{
temp = lhs;
lhs = rhs;
rhs = temp;
OnPropertyChanged(otherPropertyName);
}
}
和此的“Min”属性 setter :
min = value;
SwapIfGreater<Int32>(ref min, ref max, "Max");
OnPropertyChanged("Min");
我错过了什么?这仍然只是在Min大于Max时将Max设置为Min。
编辑:虽然我很想知道我在上面做错了什么,但再次测试了实现我想要复制的交换行为的用户界面后,我意识到这是一个令人讨厌的用户体验,因为用户被迫再次单击两个选择器。如果用户选择的 Min 高于 Max,反之亦然,我将恢复到将 Max 重置为“No Maximum”的原始实现。
最佳答案
您不能通过 ref 传递属性,因为属性被转换为 getter 和 setter 方法。
改用属性的支持字段
SwapIfGreater<Int32>(ref min, ref max);
关于c# - 如何在 ViewModel 中交换属性值?无法通过 ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40566202/
我是一名优秀的程序员,十分优秀!