我正在尝试更改属性上的isChecked值,但值不会更改。我尝试了各种各样的东西,但似乎无法解决它。在进行双向绑定时我是否需要实现INotifyPropertyChanged?我是新手,所以这对我来说有点混乱。我正在尝试遵循MVVM模式。
<ListView ItemsSource="{Binding Servers}" Margin="8,30,10,68">
<ListView.View>
<GridView>
<GridViewColumn Width="90" Header="Select For Sync">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Tag="{Binding NodeName}" IsChecked="{Binding isChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="280" Header="Pad Name"
DisplayMemberBinding="{Binding NodeName}" />
</GridView>
</ListView.View>
</ListView>
public class Server
{
#region Server Properties
public string NodeName{ get; set; }
public bool isChecked { get; set; }
#endregion
}
List<Server> checkedRows = Servers.Where(s => s.isChecked).ToList();
foreach(Server obj in Servers)
{
Console.WriteLine($"Server: {obj.NodeName}\nChecked:{obj.isChecked.ToString()}");
}
编辑:项目源在viewmodel中定义,如下所示:
public ObservableCollection<Server> Servers { get; set; }
答案 0 :(得分:1)
所以这就是经典的Double ViewModel Fake-Out的变种:
<Window.Resources>
<Client:VMConvergence x:Key="convergenceVM" />
</Window.Resources>
<Window.DataContext>
<Client:VMConvergence/>
</Window.DataContext>
...
<Button
x:Name="btnDeploy"
Content="Sync System Changes"
HorizontalAlignment="Left" Margin="8,208,0,0"
VerticalAlignment="Top"
Width="366"
Command="{Binding simple.ConvergenceModel.simple, Source={StaticResource convergenceVM}}"
/>
<ListView ItemsSource="{Binding Servers}" Margin="8,30,10,68">
<!-- ... -->
一切都很好,绑定工作得很好,但是OP通过在viewmodel的另一个实例上调用命令来检查值。
轻松修复:删除convergenceVM
资源,并更改绑定,让其使用继承的DataContext
作为其来源:
Command="{Binding simple.ConvergenceModel.simple}"
答案 1 :(得分:-1)
您应该尝试使用RelativeSource
。
像
<CheckBox Tag="{Binding NodeName}" IsChecked="{Binding DataContext.isChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=GridViewCell,Mode=FindAncestor}}"/>