Contentcontrol не находит мою таблицу данных, это ViewModel - PullRequest
2 голосов
/ 27 октября 2011

Я использую WPF, MVVM и PRISM.Я получил табличку с данными в своем представлении, связанную с ViewModel UC2002_RFPBeheren_ViewModel, поскольку страница, на которой этот код включен, связана с другой моделью представления, и я хочу, чтобы кнопка имела UC2002_RFPBeheren_ViewModel в виде ViewModel.

этого данныхUC2002_RFPBeheren_ProjectInfo_ViewModel, но я хочу, чтобы SaveButton использовал ViewModel UC2002_RFPBeheren_ViewModel

Вот мой код:

<UserControl.Resources>
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../Resources/RFPModuleResources.xaml" />
        <ResourceDictionary>
            <DataTemplate x:Key="SaveButton" DataType="{x:Type vm:UC2002_RFPBeheren_ViewModel}">
                <Button Command="{Binding SaveRFPCommand}">Save</Button>
            </DataTemplate>
        </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>

<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
   <ContentControl ContentTemplate="{StaticResource SaveButton}"/>
   <Button Command="{Binding CloseTabCommand}">Close</Button>
</StackPanel>

Хотя SaveButton отображается, но не реагирует на мою команду.Я что-то забыл или есть другой способ решить это?Заранее спасибо;)!

============================================================================================

РЕДАКТИРОВАТЬ:

Итак, я внес некоторые изменения, но они все еще не работают.

Пример кода:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Resources/RFPModuleResources.xaml" />
            <ResourceDictionary>
                <DataTemplate x:Key="SaveButton" DataType="{x:Type vm:UC2002_RFPBeheren_ViewModel}">
                    <Button Command="{Binding SaveRFPCommand}">Save</Button>
                </DataTemplate>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

Я установил это свойство вViewModel страницы

public UC2002_RFPBeheren_ViewModel MySaveVM { get; set; }

Моя панель стека теперь выглядит так:

<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
    <ContentControl Content="{Binding MySaveVM}" ContentTemplate="{StaticResource SaveButton}"/>
    <Button Command="{Binding CloseTabCommand}">Close</Button>
</StackPanel>

Ответы [ 3 ]

3 голосов
/ 27 октября 2011

что произойдет, если вы установите свой экземпляр UV2002_RFPBeheren_ViewModel в качестве содержимого для ContentPresenter?

 <ContentControl Content="{Binding MyUV2002_RFPBeheren_ViewModel}"/>

DataTemplate просто говорит, как должна отображаться ваша Viewmodel, но вы должны установить DataContext или Binding для экземпляра вашей viewmodel.

EDIT:

пример

 public class VMFoo
 {
     public UV2002_RFPBeheren_ViewModel MySaveVM {get; set;}
 }

xaml

<UserControl.Resources>
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../Resources/RFPModuleResources.xaml" />
        <ResourceDictionary>
            <DataTemplate x:Key="SaveButton" DataType="{x:Type vm:UC2002_RFPBeheren_ViewModel}">
                <Button Command="{Binding SaveRFPCommand}">Save</Button>
            </DataTemplate>
        </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<UserControl.DataContext>
   <x:local VMFoo/>
</UserControl.DataContext>
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
   <ContentControl Content="{Binding MySaveVM}"/>
   <Button Command="{Binding CloseTabCommand}">Close</Button>
</StackPanel>

РЕДАКТИРОВАТЬ: Малый рабочий образец

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type WpfApplication1:UV2002_RFPBeheren_ViewModel}">
            <Button Command="{Binding SaveRFPCommand}">Save</Button>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>
<Grid> 
    <Grid.DataContext>
        <WpfApplication1:VMFoo/>
    </Grid.DataContext>
    <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
        <ContentControl Content="{Binding MySaveVM}"/>
        <Button Command="{Binding CloseTabCommand}">Close</Button>
    </StackPanel>
</Grid>
</Window>

ViewModels

public class VMFoo
{
    public VMFoo()
    {
        this.MySaveVM = new UV2002_RFPBeheren_ViewModel();
    }
    public UV2002_RFPBeheren_ViewModel MySaveVM { get; set; }
}

public class UV2002_RFPBeheren_ViewModel
{
    private DelegateCommand _save;
    public ICommand SaveRFPCommand
    {
        get{if(this._save==null)
        {
            this._save = new DelegateCommand(()=>MessageBox.Show("success"),()=>true);
        }
            return this._save;
        }
    }
}
2 голосов
/ 27 октября 2011

Это связано с тем, как работает ContentControl.Предполагается, что вещи в ContentTemplate связаны с контентом, и поэтому DataContext устанавливается на Content, и, следовательно, это DataContext, к которому кнопка в шаблоне имеет доступ.Вы не указали Content, поэтому значение равно нулю, поэтому DataContext явно имеет значение null.Вы можете увидеть это в простом примере.Единственное, что вы можете сделать, это связать ContentControl с DataContext - см. Последний контроль содержимого в примере.

<StackPanel DataContext="Foo">  
  <StackPanel.Resources>
    <DataTemplate x:Key="withBtn">
      <Button Content="{Binding}" />
    </DataTemplate>
  </StackPanel.Resources>
  <Button Content="{Binding}" />
  <ContentControl ContentTemplate="{StaticResource withBtn}" />
  <ContentControl Content="{Binding}" ContentTemplate="{StaticResource withBtn}" />
</StackPanel>
1 голос
/ 27 октября 2011

Если вы используете MVVM, вы должны предоставить некоторый экземпляр UC2002_RFPBeheren_ViewModel в вашей UC2002_RFPBeheren_ProjectInfo_ViewModel для привязки. Либо как свойство, либо как элемент коллекции, которая является свойством.

Все в представлении должно быть в конечном итоге доступно из ViewModel, который является вашим контекстом данных (UC2002_RFPBeheren_ProjectInfo_ViewModel)

...