作为类的实现细节的数据不应该是公开的,但在我看来,你甚至不应该想绑定到这种类型的数据。绑定到视图的数据应该是视图模型的公共属性和命令。请记住,视图模型定义了您的 UI 是什么。
用户界面不允许更改的公共属性应该只实现 getter,而不是 setter。只能在某些条件下更改的公共属性应在设置器中强制执行这些条件。视图模型应该提供并容纳所有的 UI 逻辑(属性和命令)。
您还应该将视图模型包装在测试所有这些的单元测试中。
根据评论反馈更新:
class MyViewModel : ViewModelBase
{
private bool _showSomething;
public bool ShowSomething
{
get { return _showSomething; }
set
{
_showSomething = value;
RaisePropertyChanged("ShowSomething");
RaisePropertyChanged("TheThing");
}
}
public Something TheThing
{
get
{
if(_showSomething) { return _theThing; }
return _theOtherThing;
}
}
private Something _theThing;
private Something _theOtherThing;
}
编辑*:根据评论,以下内容可能更接近于所需内容。
public interface IQueryControl
{
string Query { get; set; } //view passes query in
ReadOnlyCollection<string> QueryResultDescriptions { get; } //bind to combo items
string SelectedQueryDescription { get; set; } //bind to combo selection
object SelectedItem { get; } //resulting object
}
public class UserControlVM : ViewModelBase, IQueryControl
{
private string _query;
private ObservableCollection<object> _queryResults;
private ReadOnlyCollection<string> _externalResults;
private object _selectedResult;
public string Query
{
get { return _query; }
set
{
_query = value;
RaisePropertyChanged("Query");
UpdateQueryResults();
}
}
private void UpdateQueryResults()
{
//Do query which allocates / updates _queryResults;
_externalResults = new ReadOnlyCollection<string>((from entry in _queryResults select entry.ToString()).ToList<string>());
RaisePropertyChanged("QueryResultDescriptions");
}
public ReadOnlyCollection<string> QueryResultDescriptions
{
get { return _externalResults; }
}
public string SelectedQueryDescription
{
get { return _selectedResult.ToString(); }
set
{
SelectResult(value);
}
}
private void SelectResult(string value)
{
Dictionary<string, object> lookup = _queryResults.ToDictionary<object, string>((result) => { return result.ToString(); });
if (lookup.ContainsKey(value))
{
_selectedResult = lookup[value];
RaisePropertyChanged("SelectedQueryDescription");
RaisePropertyChanged("SelectedItem");
}
else
{
//throw something
}
}
public object SelectedItem
{
get { return _selectedResult; }
}
}