2012-06-26 4 views
0

Вот моя настройка, кажется, я не привязываю данные правильно. Результатом должна быть кнопка с изображением и отображаемым текстом. Ничего не отображается.Как правильно привязать данные к кнопке WPF с помощью MVVM

<UserControl x:Class="AmebaPrototype.UI.LandingPivot.featureControl" 
     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" 
     mc:Ignorable="d" 
     d:DesignHeight="330" d:DesignWidth="960" 
     DataContext="{Binding Source={StaticResource viewModelLocator}, Path=VideoViewModel}" 
     > 
<UserControl.Resources > 
    <DataTemplate x:Key="custTemplate" > 
     <StackPanel > 
      <Image Source="{Binding ImagePath}"/> 
      <TextBlock Text="{Binding MyTitle}"/> 
     </StackPanel>   
    </DataTemplate> 
</UserControl.Resources> 

<Grid x:Name="LayoutRoot" Background="{x:Null}" > 
    <Button Content="Button" Height="316" 
      HorizontalAlignment="Left" Margin="12,2,0,0" 
      Name="button1" VerticalAlignment="Top" 
      Width="423" Click="button1_Click" 
      ContentTemplate="{DynamicResource custTemplate}" 
      /> 
    <Button Content="Button" Height="156" HorizontalAlignment="Left" Margin="441,2,0,0" Name="button2" VerticalAlignment="Top" Width="208" Click="button2_Click" /> 
    <Button Content="Button" Height="156" HorizontalAlignment="Left" Margin="669,2,0,0" Name="button3" VerticalAlignment="Top" Width="208" /> 
    <Button Content="Button" Height="156" HorizontalAlignment="Left" Margin="441,162,0,0" Name="button4" VerticalAlignment="Top" Width="208" /> 
    <Button Content="Button" Height="156" HorizontalAlignment="Left" Margin="669,162,0,0" Name="button5" VerticalAlignment="Top" Width="208" /> 
</Grid> 


Модель:

public class Video 
    { 
     public string MyTitle { get; set; } 
     public string ImagePath { get; set; } 
    } 

ViewModel

public ViewModel VideoViewModel 
    { 
     get 
     { 
      if(viewmodel == null) 
      { 
       viewmodel = new ViewModel(); 
       viewmodel.ListData.Clear(); 
       viewmodel.ListData.Add(new Video { MyTitle = "Title1", ImagePath = "exampleimage.com/image.png" }); 
       viewmodel.ListData.Add(new Video { MyTitle = "Title2", ImagePath = "exampleimage.com/image.png" }); 

      } 

      return viewmodel; 
     } 
    } 
+0

Как выглядит ваш «VideoViewModel»? Потому что в 'DataContext' UserControl' вы привязываетесь к' VideoViewModel', который не является самим классом «Video», но содержит (я думаю) свойство с типом «Видео». – nemesv

+0

Установите ссылку для привязки к кнопке с помощью MVVM: http://stackoverflow.com/questions/3772797/wpf-mvvm-button-control-binding-in-datatemplate – Ponmalar

+0

Когда вы запускаете свою программу, посмотрите на панель «Вывод» в Visual Studio. Существуют ли ошибки BindingExpression? –

ответ

1

Если вы действительно хотите сделать это с помощью DataTemplate, то:

<Button> 
     <Button.Content> 
      <x:Type TypeName="Visual"/> 
     </Button.Content> 
     <Button.Template> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       <Grid> 
        <ContentPresenter ContentSource="Content"/> 
       </Grid> 
      </ControlTemplate> 
     </Button.Template> 
     <Button.ContentTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Path=Name}"/> 
      </DataTemplate> 
     </Button.ContentTemplate> 
    </Button> 

Ваше ViewModel связывание должно быть в порядке, чтобы использовать здесь, так что в DataTemplate вы можете просто настроить его, чтобы включить изображение и TextBlock.

+0

что такое x? реферирование. Пробовал это, и это не позволяет мне установить его для x: Тип. – Fabii

+0

x - это пространство имен xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml". – EdFred

0

DataTemplate ресурсов:

<DataTemplate x:Key="bTemplate"> 
     <Button Label="{Binding MyTitle}" 
       Command="{Binding Execute}"> 
      <Image Source="{Binding ImagePath}" /> 
     </Button> 
</DataTemplate> 

Не так, как в вашем вопросе, но тогда вы можете использовать элемент управления, который принимает ItemSource, такие как ListView:

<ListView 
    ItemsSource="{Binding ListData}" 
    ItemTemplate="{StaticResource bTemplate}" 
> 
</ListView> 

я добавил команду, так как это необходимо, если вы хотите реализовать MVVM, а не щелчок по событию.

+0

Я реализовал его с помощью ListView и ListBox раньше, но теперь мне нужно реализовать только Button специально. i) нет ListView или других макетов. – Fabii

Смежные вопросы