小编PT2*_*550的帖子

仅当属性存在时才绑定到属性

我有一个 WPF 窗口,它使用多个 viewmodel 对象作为其 DataContext。该窗口有一个控件,该控件绑定到仅存在于某些视图模型对象中的属性。如果该属性存在(并且仅当它存在),我如何绑定到该属性。

我知道以下问题/答案:MVVM - 当绑定属性不存在时隐藏控件。这有效,但给了我一个警告。可以在没有警告的情况下完成吗?

谢谢!

一些示例代码:

Xml:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="40"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListBox Grid.Row="1" Name="ListView" Margin="25,0,25,0" ItemsSource="{Binding Path=Lst}"
              HorizontalContentAlignment="Center" SelectionChanged="Lst_SelectionChanged">
    </ListBox>
    <local:SubControl Grid.Row="3" x:Name="subControl" DataContext="{Binding Path=SelectedVM}"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

子控件 Xaml:

<UserControl x:Class="WpfApplication1.SubControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:WpfApplication1"
         mc:Ignorable="d" 
         d:DesignHeight="200" d:DesignWidth="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="40"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="1" Orientation ="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,5,0,5">
        <TextBlock Margin="5,0,5,0" …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml mvvm

6
推荐指数
1
解决办法
2805
查看次数

标签 统计

c# ×1

mvvm ×1

wpf ×1

xaml ×1