c# - 为什么我的模板的文本框无法绑定(bind)

标签 c# wpf xaml mvvm

我正在尝试做一些绑定(bind)。在大多数情况下,我的 MVVM 应用程序运行良好,但我现在想使用模板。在这种情况下,我使用的是 XCeed 图表,它公开了 SeriesTemplate .

我的代码是:

  <UserControl
 xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" 
          x:Class="MyApp.AppUi.View.Graph.GraphView"
         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:converter="clr-namespace:MyApp.AppUi.Converters" 
         >

<Grid>

    <Grid.Resources>

        <converter:MyIntConverter x:Key="MyIntConverter" />

        <DataTemplate x:Key="MyLabelTemplate">
            <TextBlock Text="{Binding Path=Text, Converter={StaticResource MyIntConverter}}" />
        </DataTemplate>

        <!--give it a name,                             Bind to above,        choose property -->
        <CollectionViewSource x:Key="GraphDataCollection" Source="{Binding GraphDataList}" />


        <Style  x:Key="TextBoxTextStyle" TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="FontFamily" Value="Comic Sans MS"/>
            <Setter Property="FontSize" Value="12"/>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Mouse.MouseEnter">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetProperty="FontSize" To="19" Duration="0:0:0.4"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>

                <EventTrigger RoutedEvent="Mouse.MouseLeave">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetProperty="FontSize" To="12" Duration="0:0:0.4" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </Style.Triggers>
        </Style>

        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <ContentPresenter/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" 
                         Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}">
                            <Rectangle RadiusX="5" RadiusY="5" >
                                <Rectangle.Triggers>
                                    <EventTrigger RoutedEvent="Mouse.MouseEnter">
                                        <EventTrigger.Actions>
                                            <BeginStoryboard>
                                                <Storyboard>
                                                    <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.8" Duration="0:0:0.4"/>
                                                </Storyboard>
                                            </BeginStoryboard>
                                        </EventTrigger.Actions>
                                    </EventTrigger>

                                    <EventTrigger RoutedEvent="Mouse.MouseLeave">
                                        <EventTrigger.Actions>
                                            <BeginStoryboard>
                                                <Storyboard>
                                                    <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.4" />
                                                </Storyboard>
                                            </BeginStoryboard>
                                        </EventTrigger.Actions>
                                    </EventTrigger>
                                </Rectangle.Triggers>

                                <Rectangle.Fill>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                                        <GradientStop Color="#FFffcf26" Offset="0.0" />
                                        <GradientStop Color="#FFff7f04" Offset="1.0" />
                                    </LinearGradientBrush>
                                </Rectangle.Fill>
                            </Rectangle>
                            <ContentPresenter VerticalAlignment="Center" Content="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"/>
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>


        <DataTemplate x:Key="SeriesTemplate">
            <Button>
                <StackPanel>
                     <TextBlock Text="{Binding GraphData.ShortDate}" Style="{StaticResource TextBoxTextStyle}" />
                </StackPanel>
            </Button>
        </DataTemplate>
    </Grid.Resources>

    <GroupBox Header="{Binding Title}">
        <GroupBox.Background>
            <LinearGradientBrush EndPoint="0,1" StartPoint="0,0" >
                <GradientStop Offset="0" Color="#FF9d9d9d" />
                <GradientStop Offset="1" Color="#FF666666" />
            </LinearGradientBrush>
        </GroupBox.Background>

        <xctk:Chart Height="400" Width="400" ShowLegend="False">

           <xctk:Chart.Areas>
            <xctk:Area >
                <xctk:Area.XAxis>

                    <xctk:Axis Title="Date" 
                                   GraduationMode="Manual" 
                                   LabelsType="DateTime"
                                   ScaleMode="Automatic"
                                   TitleMargin="10"
                                   AxisLabelsLayout="ShowAll"
                                   ShowArrow="False"
                                   ShowAxis="True"
                                   ShowGridLines="True"
                                   ShowTicks="True"
                                   ShowTickLabels="True"
                                   ShowAxisLabel="True"
                                   Reversed="False"
                                   />
                </xctk:Area.XAxis>
                <xctk:Area.YAxis>
                    <xctk:Axis Title="Google position"  
                                   ScaleMode="Manual"
                                   TitleMargin="10"
                                   AxisLabelsLayout="ShowAll"
                                   ShowArrow="False"
                                   ShowAxis="True"
                                   ShowGridLines="True"
                                   CustomRangeStart="1.00"
                                   CustomRangeEnd="111.00"
                                   ShowTicks="True"
                                   ShowTickLabels="True"
                                   ShowAxisLabel="True"
                                   Reversed="False" 
                                   LabelTemplate="{StaticResource MyLabelTemplate}"
                                   />
                </xctk:Area.YAxis>

                <xctk:Area.Series>
                        <xctk:Series DataPointsSource="{Binding Source={StaticResource GraphDataCollection}}"
                              Template="{StaticResource SeriesTemplate}"
                              ShowPointsInLegend="true">
                        <xctk:Series.DataPointBindings>
                            <xctk:BindingInfo PropertyName="Y">
                                <xctk:BindingInfo.Binding>
                                    <Binding Path="Position"/>
                                </xctk:BindingInfo.Binding>
                            </xctk:BindingInfo>
                            <xctk:BindingInfo PropertyName="X">
                                <xctk:BindingInfo.Binding>
                                        <Binding Path="Date"/>
                                </xctk:BindingInfo.Binding>
                            </xctk:BindingInfo>
                            <xctk:BindingInfo PropertyName="Label">
                                <xctk:BindingInfo.Binding>
                                    <Binding Path="ShortDate"/>
                                </xctk:BindingInfo.Binding>
                            </xctk:BindingInfo>
                        </xctk:Series.DataPointBindings>
                    </xctk:Series>
                </xctk:Area.Series>
            </xctk:Area>
        </xctk:Chart.Areas>
    </xctk:Chart>
    </GroupBox>


</Grid>

和我的 ViewModel
public class GraphViewModel : BaseViewModel
{
    public GraphViewModel(List<GraphData> data, string title )
    {
        this.GraphDataList = data;
        this.Title = title;
    }

    public string Title { get; private set; }
    public List<GraphData> GraphDataList { get; private set; }
}

并且在资源字典中设置了 DataContext
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:graphView="clr-namespace:MyApp.AppUi.View.Graph"
                xmlns:graphViewModel="clr-namespace:MyApp.AppUi.ViewModel.Graph"
                xmlns:converter="clr-namespace:MyApp.AppUi.Converters"
                >

<DataTemplate DataType="{x:Type graphViewModel:GraphViewModel}">
    <graphView:GraphView />
</DataTemplate>

图表按需要显示,但 SeriesTemplate 不绑定(bind)。输出窗口中有一条错误消息,我明白消息在说什么,但不知道如何修复它。

错误信息是

System.Windows.Data Error: 40 : BindingExpression path error: 'ShortDate' property not found on 'object' ''ColumnPrimitiveInfo' (HashCode=39288004)'. BindingExpression:Path=ShortDate; DataItem='ColumnPrimitiveInfo' (HashCode=39288004); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')



如何让绑定(bind)工作
  <DataTemplate x:Key="SeriesTemplate">
            <Button x:Name="Bar">
                <StackPanel>                       
                    <TextBlock Text="{Binding GraphData.ShortDate}" Style="{StaticResource TextBoxTextStyle}" /> <!--THIS IS WHERE THE FAULT IS -->
                </StackPanel>
            </Button>
        </DataTemplate>

XCeed 有一个 working demo附上源码,如果你下载了应用,点击Charts -> Styling -> Column Series 可以看到我的代码非常相似。有作品,但我的没有,我不明白为什么。请注意,图表本身会显示,只是文本框没有显示。但是,如果我不使用绑定(bind),只需使用 Text="SomeWords"然后它工作正常

最佳答案

经过几个小时的伏都教编程(我只是随机尝试不同的东西),我找到了解决方案。

 <TextBlock Text="{Binding Path=Content.ShortDate}" Style="{StaticResource TextBoxTextStyle}" />

我认为这是因为(请参阅 OP 代码中的按钮 setter )
 <ContentPresenter VerticalAlignment="Center" Content="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"/>

关于c# - 为什么我的模板的文本框无法绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529204/

相关文章:

c# - Entity Framework 5 删除问题 - 对象状态管理器问题

c# - BackgroundWorker 在长时间运行后停止运行

wpf - 按钮图像路径未在 wpf 中聚焦

c# - 无边框窗口无法正确最大化

c# - 防止 "The remote host closed the connection"异常的可接受方法

c# - 一旦 frame 导航到另一个 Page 就销毁 ViewModel 和 Page 的实例

c# - 使用 Dispatcher.Invoke 从 WPF 中的不同线程关闭窗口

c# - 支持定期通知的自定义 ObservableCollection<T> 或 BindingList<T>

后台线程中的 WPF 更新绑定(bind)

c# - 将 SQLite 数据填充到 UWP 应用程序中