我有自定义控件(没有MVVM),代码背后:
public partial class CustomControl : UserControl
{
public CustomControl()
{
InitializeComponent();
}
public int Position
{
get { return (int)GetValue(PositionProperty); }
set { SetValue(PositionProperty, value); }
}
public static readonly DependencyProperty PositionProperty = DependencyProperty.Register(
"Position", typeof(int), typeof(CustomControl), new PropertyMetadata(0, PositionChanged, CorrectPosition));
private static void PositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
private static object CorrectPosition(DependencyObject d, object obj)
{
var val = (int) obj;
// max value is 5
if (val > 5)
return 5;
return obj;
}
}
}
我也有ViewModel(MVVM):
public class ViewModel : BaseViewModel
{
private int _position;
public int Position
{
get { return this._position; }
set
{
this._position = value;
this.RaisePropertyChanged(() => this.Position);
}
}
}
XAML(MVVM):
<Window x:Class="MainWindow">
<CustomControl Position="{Binding Path=Position, Mode=TwoWay}" />
</Window>
当我将ViewModel的6属性设置为6时,它将为6。 但CustomControl的属性值为5。
我希望自定义控件和viewmodel具有相同的更正值。对于这种情况,这个值将是5。我不想要任何代码重复。
我需要知道如何同步位置校正?
答案 0 :(得分:0)
这个怎么样? XAML:
<CustomControl name="CustomControlPosition" Position="{Binding Path=Position, Mode=TwoWay}" />
C#:
private static void PositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
this.Position = CustomControlPosition.Position;
}
答案 1 :(得分:0)
注册自定义属性时,需要设置元数据,以便默认情况下值使用双向绑定:
public static readonly DependencyProperty PositionProperty =
DependencyProperty.Register("Position", typeof(int), typeof(CustomControl),
new PropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
PositionChanged, CorrectPosition));
请注意FrameworkPropertyMetadataOptions
枚举值。
如果此更改本身并未解决您的问题,那么您可能必须将当前处于强制值回调中的代码移动到您的属性更改回调中,并摆脱强制价值回调:
private static void PositionChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var val = (int) e.NewValue;
// max value is 5
if (val > 5)
((CustomControl) d).Position = 5;
}