在亲身体验了几个月的WPF之后,我决定尝试一下Caliburn Micro。但是我遇到了几个问题无法解决。以下是我的代码和问题:
public class MainViewModel : PropertyChangedBase
{
BindableCollection<PlayerProfile> _playerProfiles = staticInfos.Load();
public BindableCollection<PlayerProfile> PlayerProfiles {
get { return _playerProfiles; }
set {
_playerProfiles = value;
NotifyOfPropertyChange(() => PlayerList);
}
}
string _tb_AddPlayer;
public string TB_AddPlayer {
get { return _tb_AddPlayer; }
set {
_tb_AddPlayer = value;
NotifyOfPropertyChange(() => TB_AddPlayer);
NotifyOfPropertyChange(() => CanAddPlayer);
}
}
List<string> _pl = new List<string>();
public List<string> PlayerList {
get{
foreach (PlayerProfile p in PlayerProfiles) {
if (!_pl.Contains(p.Name)) _pl.Add(p.Name);
}
return _pl;
}
set {
_pl = value;
NotifyOfPropertyChange(()=>PlayerList);
}
}
// Dummy Test String
string _test;
public string Test {
get { return _test; }
set {
_test = value;
NotifyOfPropertyChange(() => Test);
}
}
// Button Action
public void AddPlayer() {
_playerProfiles.Add(new PlayerProfile(TB_AddPlayer));
Test = "Pressed";
NotifyOfPropertyChange(() => PlayerProfiles);
}
public bool CanAddPlayer {
get { return true; }
// doesnt work: get { return !string.IsNullOrWhiteSpace(TB_AddPlayer); }
}
}
所以,我使用绑定约定,即 MainView 中的属性应该绑定到 View 中同名的元素。
首先,注意 PlayerList 只是 PlayerProfiles 中玩家名称列表,我创建它是因为当绑定到 Combobox 时,如果我将 Combobox 命名为 PlayerProfiles,则它们不会显示出来,但是如果我通过列表并将其命名为 PlayerList,则它们会显示出来——尽管我已经在 PlayerProfile 类中重写了 ToString 方法。为什么?这似乎很笨拙...(如果你想知道,staticInfos.Load() 方法会将 PlayerProfiles 填充为几个虚拟名称...)
当我在文本框(称为 TB_AddPlayer)中键入内容并按下按钮(称为 AddPlayer)时,测试字符串会出现,所以我知道操作已经发生,但是新名称不会出现在组合框中。
此外,如果我使用 CanAddPlayer 属性中的注释行,则按钮永远不会启用,无论我何时开始输入,还是当文本框失去焦点时有文本。为什么?
抱歉问这些基础问题,我已经盯着“Hello World”caliburn示例看了几个小时,但不知道我错过了什么...提前致谢!
编辑:这是 .xaml 文件。
<UserControl x:Class="MixGameM8_MVVM.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MixGameM8_MVVM.Views">
<UserControl.Resources>
<Style TargetType="TextBlock" x:Key="TB_A">
<Setter Property="Margin" Value="5,5,5,5" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontSize" Value="15" />
</Style>
<!-- ... Some more of this kind -->
</UserControl.Resources>
<Grid>
<!-- ... Grid definitions -->
<Border Style="{StaticResource Border_A}" Grid.Row="0" Grid.Column="0">
<StackPanel Name="SP_Controls">
<TextBlock Style="{StaticResource TB_A}" Text="Controls"/>
<ComboBox Style="{StaticResource CB_A}" Name="PlayerProfiles"/>
<StackPanel Orientation="Horizontal">
<TextBox Style="{StaticResource TBox_A}" Name="TB_AddPlayer" MinWidth ="100" />
<Button Style="{StaticResource Button_AddPlayer}" Content="Add Player" Name="AddPlayer" />
</StackPanel>
</StackPanel>
</Border>
<!-- ... And some more cells in the grid, one containing the dummy textbox -->
</Grid>
</UserControl>
MainView
XAML 代码? - nemesv