问题描述
我正在对Entry进行自定义控件,我需要获取x:Entry的名称才能在项目的viewmodel中使用它,以便在使用它时获得光标位置。
这是我的代码:
这是我自定义控件的xaml:
<Entry
x:Name="EntryControl"
Margin="45,0"
Placeholder="{Binding Source={x:Reference CKEditorView},Path=Placeholder}"
Text="{Binding EntryText}"
WidthRequest="320" />
我想获得此x:Name在viewmodel中使用。
解决方法
正如@Jason所说,您可以绑定 CursorPosition 的值。
该属性是可绑定的,因此我们可以将其设置为
<Entry
CursorPosition="{Binding Position,Mode=TwoWay}"
x:Name="EntryControl"
Margin="45,0"
Placeholder="{Binding Source={x:Reference CKEditorView},Path=Placeholder}"
Text="{Binding EntryText}"
WidthRequest="320" />
在ViewModel中
public class MainViewModel : INotifyPropertyChanged
{
public ObservableCollection<Color> MySource { get; set; }
int position;
public int Position
{
get
{
return position;
}
set
{
// it will been called when we edit the entry
if(position != value)
{
position = value;
OnPropertyChanged("Position");
// do some thing you want
}
}
}
public MainViewModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
}
}