无法对TextBox执行同等的文本绑定
本文关键字:文本 绑定 执行 TextBox | 更新日期: 2023-09-27 18:02:40
在我的程序中,我有一个绑定到数据模型中的属性值的TextBlock
。我想将这个TextBlock
更改为TextBox
,以便它是可编辑的,但仍然想将文本绑定到它。问题是,当我将TextBlock
更改为TextBox
时,我的绑定不起作用,TextBox
显示空白。
我要绑定到的属性是程序中已有的自定义类的属性。
这是属性:
//Property for Display Name
public MultiItemString DisplayName {}
这是MultiItemString
类:
public class MultiItemString : INotifyPropertyChanged
{
private readonly string[] _keys;
private readonly MultiItemString[] _nestedItems;
readonly bool _resourceKey;
private readonly bool _nestedMultiItemStrings;
public MultiItemString(IEnumerable<string> keys, bool resourceKey = true)
{
_keys = keys.ToArray();
_resourceKey = resourceKey;
LanguageChange.LanguageChagned += (sender, args) => RaisePropertyChanged("");
}
public MultiItemString(IEnumerable<MultiItemString> nestedItems)
{
_nestedItems = nestedItems.ToArray();
foreach (var multiItemString in _nestedItems)
{
multiItemString.PropertyChanged += (s, e) => RaisePropertyChanged("Value");
}
_nestedMultiItemStrings = true;
}
public string Key
{
get
{
if (_keys != null && _keys.Length != 0) return _keys[0];
return null;
}
}
public string Value
{
get
{
var sb = new StringBuilder();
if (_nestedMultiItemStrings)
{
foreach (var MultiItemString in _nestedItems)
{
sb.Append(MultiItemString.Value);
}
}
else
{
foreach (var key in _keys)
{
sb.Append(_resourceKey ? (string)Application.Current.Resources[key] : key);
}
}
return sb.ToString();
}
}
public override string ToString()
{
return Value;
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propertyName)
{
var temp = PropertyChanged;
if (temp != null)
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
我的xaml :
<TextBox Text="{Binding Model.DisplayName}" Height="28" HorizontalAlignment="Left" Name="title_TB" VerticalAlignment="Top" Width="Auto" FontWeight="Bold" FontSize="14" Margin="5,2,0,0" />
如何将此属性绑定到TextBox
作为文本值,就像我对TextBlock
一样?
应该可以:
<TextBox Text="{Binding Model.DisplayName.Value}" Height="28" HorizontalAlignment="Left" Name="title_TB" VerticalAlignment="Top" Width="Auto" FontWeight="Bold" FontSize="14" Margin="5,2,0,0" />
并且,更新Value属性使其具有setter:
private string _thisShouldBeAValidField ;
public string Value
{
get
{
if(_thisShouldBeAValidField!=null) return _thisShouldBeAValidField;
var sb = new StringBuilder();
if (_nestedMultiItemStrings)
{
foreach (var MultiItemString in _nestedItems)
{
sb.Append(MultiItemString.Value);
}
}
else
{
foreach (var key in _keys)
{
sb.Append(_resourceKey ? (string)Application.Current.Resources[key] : key);
}
}
return sb.ToString();
}
set{
_thisShouldBeAValidField = value;
}
}