我的文本块未更新从我的模型更新值。如果我更新ViewModel中的文本块,它会起作用,所以我的绑定似乎是正确的。我相信问题是我在模型中更新它的方式,但我不确定为什么我的observableCollection也只是更新,因为我来回传递值并不确定这是不错的MVVM策略。textblock在属性更改时未更新
XAML部分:
<Grid>
<TextBox x:Name="NewLabelBx" HorizontalAlignment="Left" Height="23" Margin="54,449,0,0" TextWrapping="Wrap" Text="{Binding NewLabel,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="314"/>
<Button x:Name="NewLabelBtn" Content="Add Label" HorizontalAlignment="Left" Margin="293,490,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.518,-0.709" Command="{Binding Path=NewLabelBtn}" />
<TextBlock x:Name="FilesProcessedBlck" HorizontalAlignment="Left" Margin="54,507,0,0" TextWrapping="Wrap" Text="{Binding FilesProcessedBlck, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" RenderTransformOrigin="-0.7,0.562" Width="65"/>
</Grid>
视图模型部分:
public class P4LabelBatteryViewModel : BindableBase
{
private P4LabelBatteryModel p4LabelBatteryModel = new P4LabelBatteryModel();
public P4LabelBatteryViewModel()
{
P4LabelBatteryModel p4LabelBatteryModel = new P4LabelBatteryModel();
this.GetBatteryBtn = new DelegateCommand(chooseFile, canChooseFile);
this.NewLabelBtn = new DelegateCommand(chooseNewLabel, canNewLabel).ObservesProperty(() => NewLabel);
this.FilesProcessedBlck = 2; //this works.
}
//other code here
private void chooseNewLabel()
{
if (ScriptCollection.Count > 0)
{
ScriptCollection = P4LabelBatteryModel.TagsFilesModel(NewLabel, ScriptCollection);
}
}
private int _filesProcessedBlck;
public int FilesProcessedBlck
{
get
{
return _filesProcessedBlck;
}
set
{
SetProperty(ref _filesProcessedBlck, value);
}
}
private ObservableCollection<ScriptModel> _scriptCollection = new ObservableCollection<ScriptModel>();
public ObservableCollection<ScriptModel> ScriptCollection
{
get
{
return _scriptCollection;
}
set
{
SetProperty(ref _scriptCollection, value);
}
}
}
Model部分:
class P4LabelBatteryModel
{
public static ObservableCollection<ScriptModel> TagsFilesModel(string NewLabel, ObservableCollection<ScriptModel> observableCollection)
{
string newLabel = NewLabel;
var scriptsToTagColl = observableCollection;
string[] files = null;
var _p4LabelBatteryViewModel = new P4LabelBatteryViewModel();
_p4LabelBatteryViewModel.FilesProcessedBlck++; //xaml is never updated with this value.
//This will generate an IPC when returned
ObservableCollection<ScriptModel> newCollection = new ObservableCollection<ScriptModel>();
//code here that modifies newCollection xaml updates when this returns, _p4LabelBatteryViewModel.FilesProcessedBlck++; does not.
return newCollection;
}
}
当我运行调试器我可以看到P4LabelBatteryViewModel.FilesProcessedBlck被修改但XAML没有被更新。
看起来像'.DataContext'问题。看起来你没有正确指定它,所以当你在你的'ObservableCollection'代码中创建第二个实例时,你的TextBlock指向'P4LabelBatteryViewModel'的一个实例。 – Rachel