如何在 DataTemplate 中绑定两个不同的类属性
如果您将 Visibility 与 绑定StaticResource
,请在您的页面中声明 ViewModel 类,Resources
如下所示。
视图模型
public class ViewModel
{
public ViewModel()
{
Visibility = false;
}
public bool Visibility { get; set; }
}
Xaml
<Page.Resources>
<local:ViewModel x:Key="ViewModel" />
</Page.Resources>
<DataTemplate x:DataType="local:Item">
<TextBlock
Width="100"
Height="44"
Text="{x:Bind Name}"
Visibility="{Binding Visibility, Source={StaticResource ViewModel}}" />
</StackPanel>
</DataTemplate>
更新
如果您希望在运行时动态更改可见性值,则需要为 ViewModel 类实现 INotifyPropertyChanged 接口。
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
Visibility = false;
}
private bool _visibility;
public bool Visibility
{
get
{
return _visibility;
}
set
{
_visibility = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}
更多细节请参考Data binding in depth官方文档。