gpt4 book ai didi

c# - WPF View-ModelView 绑定(bind)需要帮助请

转载 作者:行者123 更新时间:2023-12-03 10:30:28 25 4
gpt4 key购买 nike

我一直在四处寻找如何将模型 View 绑定(bind)到 View ,但我似乎无法解决。
我有一个名为 Search 的 View ,我想将它绑定(bind)到 SearchModelView。
View 有一个按钮和一个文本框,看起来:

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >

<ComboBox Height="23" HorizontalAlignment="Left" Margin="12,40,0,0" Name="comboBox1" VerticalAlignment="Top" Width="174" />
<Label Content="Client:" Height="28" HorizontalAlignment="Left" Margin="0,12,0,0" Name="label1" VerticalAlignment="Top" Width="71" />
<Label Content="Client Reference:" Height="28" HorizontalAlignment="Left" Margin="0,69,0,0" Name="label2" VerticalAlignment="Top" Width="117" />
<TextBox
x:Name="clientRefTxt"
Text="{Binding Path=ClientRef, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
Height="23"
HorizontalAlignment="Left"
Margin="12,103,0,0"
VerticalAlignment="Top"
Width="174" />
<Button
Content="Search Debtors"
Height="23"
HorizontalAlignment="Left"
Margin="12,140,0,0"
Name="button1"
VerticalAlignment="Top"
Width="89"
Command="{Binding Path=SearchCommand}"/>

</Grid>

我希望它绑定(bind)到 SearchViewModel:

命名空间 Master.ViewModel
{
public class SearchViewModel:WorkspaceViewModel
{
RelayCommand _searchCommand;
readonly Search _search;


#region Search Properties
public string ClientRef
{

get { MessageBox.Show("GET CLIENTREF"); return _search.ClientRef; }
set
{
MessageBox.Show("SET CLIENTREF");
if (value == _search.ClientRef)
return;
_search.ClientRef = value;
base.OnPropertyChanged("ClientRef");
}
}

#endregion

public ICommand SearchCommand
{
get
{
MessageBox.Show("SEARCHCOMMAND");

if (_searchCommand == null)
{
_searchCommand = new RelayCommand(
param=> this.Search(),
param=> this.CanSearch
);
}
return _searchCommand;
}
}

public void Search()
{
MessageBox.Show("SEARCHING");
}

bool CanSearch
{
get { return true; }
}
}

}

我删除了顶部的所有组件,但假设它们都在那里。另请注意,SearchViewModel 在单独的 dll 中,而不是在带有 View 的 exe 中。
任何帮助都会很好,或者至少是写方向的指针,我已经阅读了关于 MVVM 的 msdn 文章,但这并没有帮助......我有点需要更好地了解绑定(bind)这些内容。
提前致谢。
附言
更多细节:
SearchViewModel 属于 Master.ViewModel
SearchView 是 GUI.View 的一部分
我知道绑定(bind)对象是如何工作的,我不确定如何将 View 绑定(bind)到 View 模型

最佳答案

您的 View 是网格吗?我只使用了 UserControl 或 Window 类型作为 View ,但使用 Grid 可能会成功。

无论如何,这是用 UserControl View 实例化 ViewModel 的最简洁方法。如果您使用网格,只需将 UserControl 标记替换为 Grid 标记。

<UserControl ...(blah blah)
xmlns:viewmodel="clr-namespace:Master.ViewModel">
<UserControl.DataContext>
<viewmodel:SearchViewModel/>
</UserControl.DataContext>

我相信,除非必要,否则远离 View 的代码是 MVVM 的首选模式 - 让 XAML 尽可能为您连接。

关于c# - WPF View-ModelView 绑定(bind)需要帮助请,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com